Dynamic Memory Allocation in C (malloc, calloc, realloc, free)
On this page (10sections)
About this page
This page focuses on dynamic (heap) memory — malloc, calloc, realloc and free with code examples. For the broader picture including static and stack memory, see Memory management In C.
Introduction
Stack memory is automatic and limited. Dynamic memory is allocated from the heap at runtime using malloc, calloc, and realloc. You must release it with free to avoid memory leaks.
Key Functions
| Function | Purpose |
|---|---|
malloc(size) | Allocate uninitialized bytes |
calloc(n, size) | Allocate and zero-initialize n elements |
realloc(ptr, size) | Resize existing block |
free(ptr) | Release memory |
All are declared in <stdlib.h>.
Example — malloc and free
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5, i;
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (i = 0; i < n; i++)
arr[i] = (i + 1) * 10;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
free(arr);
arr = NULL;
return 0;
}
Sample Output
10 20 30 40 50
calloc Example
int *zeros = (int *)calloc(10, sizeof(int)); /* all bytes set to 0 */
realloc Example
arr = (int *)realloc(arr, 10 * sizeof(int)); /* grow array */
if (arr == NULL) { /* handle failure — original block may still exist */ }
Best Practices
- Always check for
NULLafter allocation. - Set pointer to
NULLafterfreeto avoid double-free bugs. - Match every
malloc/calloc/reallocwith exactly onefree. - Prefer
callocwhen you need zero-initialized memory.
Common Mistakes
- Memory leak — forgetting
free. - Double free — calling
freetwice on the same pointer. - Dangling pointer — using memory after
free. - Wrong size —
malloc(n)instead ofmalloc(n * sizeof(type)).
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- Memory management In C — Concept — static, stack and heap memory.
- File Management — More in c advance.
- Storage Classes In C — More in c advance.