Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to C
C Memory Management Explained

C Memory Management Explained

C935 viewsBy Admin
cmemorymanagement

Manual Memory Management

Unlike Python or Java, C has no garbage collector. You allocate and free memory yourself, which gives control but demands discipline.

Stack vs Heap

StackHeap
SpeedFastSlower
SizeLimitedLarge
LifetimeAuto (scope)Manual (free)

The Four Allocation Functions

int *a = malloc(sizeof(int) * 10);   // uninitialised
int *b = calloc(10, sizeof(int));    // zero-initialised
b = realloc(b, sizeof(int) * 20);    // resize
free(a); free(b);                    // release

Avoiding Memory Leaks

  • Every malloc needs a matching free.
  • Set pointers to NULL after freeing.
  • Use tools like Valgrind to detect leaks.

FAQs

What is a dangling pointer?

A pointer to memory that's already been freed. Using it is undefined behaviour. More in our C guides.

Double free?

Calling free twice on the same pointer crashes — set it to NULL after freeing.