Dynamic Memory Allocation in C (malloc, calloc, realloc, free)
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 50calloc 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
Common Mistakes
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.
Frequently Asked Questions
What does this C program do?
It is a C example program that demonstrates Dynamic Memory Allocation in C (malloc, calloc, realloc, free), including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and conditional logic, illustrating a common pattern in C programming.