C Memory Management Explained
Ad
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
| Stack | Heap | |
|---|---|---|
| Speed | Fast | Slower |
| Size | Limited | Large |
| Lifetime | Auto (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
mallocneeds a matchingfree. - Set pointers to
NULLafter 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.
