Dynamic Memory Allocation: malloc, calloc, realloc & free
Allocate memory at runtime on the Heap using malloc, calloc, realloc, and prevent memory leaks with free.
- Stack memory is fixed and scoped to function execution; Heap memory persists until explicitly freed.
malloc(size)allocates uninitialized raw bytes on the heap.calloc(num, size)allocates contiguous memory and initializes all bytes to zero.realloc(ptr, new_size)dynamically expands or contracts previously allocated heap memory.free(ptr)releases heap memory back to the operating system allocator.- Failing to free heap memory leads to progressive memory leaks.
The 4 Pillars of Dynamic Memory (<stdlib.h>)
When data sizes cannot be predicted ahead of time (such as dynamic user inputs, network sockets, or resizable lists), dynamic memory allocation is essential. C provides 4 core functions in <stdlib.h>:
If system memory is exhausted, malloc and calloc return NULL. Always verify `if (ptr == NULL)` before accessing the allocated memory!
| Function | Standard Signature | Purpose & Allocation Behaviour |
|---|---|---|
| malloc() | void* malloc(size_t size) | Allocates 'size' bytes on the Heap. Leaves memory uninitialized (contains random garbage bytes). |
| calloc() | void* calloc(size_t num, size_t size) | Allocates 'num * size' bytes and clears every single byte to zero (0). |
| realloc() | void* realloc(void *ptr, size_t new_size) | Expands or contracts an existing heap block. Relocates data if contiguous space is unavailable. |
| free() | void free(void *ptr) | Releases the allocated heap block back to the OS allocator. Does NOT nullify the pointer. |
Dynamic Array with Resizing
Here is how modern C programs create expandable dynamic arrays on the heap:
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 2 correct(0 attempted)
What is the primary difference between malloc() and calloc()?
IntermediateWhat happens if you do not call free() on memory allocated with malloc() before a long-running program continues?
Intermediate