Dynamic Memory Allocation in C
Until now, all the memory we used in C programs was fixed.
Arrays had a fixed size, variables occupied fixed space, and everything was decided before the program started running.
But real programs don’t always know in advance:
- How much data will be needed
- How many users will interact
- How large input will be
This is where dynamic memory allocation becomes essential.
What Is Dynamic Memory?
Dynamic memory is memory that is:
- Allocated while the program is running
- Controlled manually by the programmer
- Stored in the heap memory
Unlike stack memory, heap memory stays available until you explicitly release it.
Why Dynamic Allocation Is Needed
Consider this problem:
int arr[100];
What if the user wants to store 10 elements?
What if the user wants to store 10,000 elements?
Fixed memory wastes space or becomes insufficient. Dynamic allocation solves this.
Memory Allocation Functions
C provides four important functions:
- malloc()
- calloc()
- realloc()
- free()
These functions are declared in:
#include <stdlib.h>
malloc() – Memory Allocation
malloc allocates a block of memory of given size.
int *ptr;
ptr = (int*) malloc(5 * sizeof(int));
Explanation:
- Allocates memory for 5 integers
- Returns starting address
- Memory is uninitialized (garbage values)
Using malloc Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int*) malloc(3 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
printf("%d %d %d", arr[0], arr[1], arr[2]);
free(arr);
return 0;
}
calloc() – Clear Allocation
calloc works like malloc, but:
- Allocates memory
- Initializes all values to zero
int *ptr = (int*) calloc(5, sizeof(int));
Difference from malloc:
- malloc → garbage values
- calloc → all zeros
realloc() – Resize Memory
Sometimes you need more memory later.
realloc allows resizing existing memory.
ptr = realloc(ptr, 10 * sizeof(int));
It:
- Expands or shrinks memory
- Keeps old data if possible
free() – Release Memory
Every dynamically allocated memory must be released.
free(ptr);
If you forget to free memory, it causes:
- Memory leaks
- Program slowdown
- Crashes in long-running applications
Real-World Analogy
Think of heap memory like renting a room:
- You rent when needed
- You pay while using
- You must return it when done
malloc / calloc → renting free → returning
Mini Practice
- Allocate memory for 5 integers
- Store values
- Print them
- Free memory
Quick Quiz
Q1. Which memory area does malloc use?
Heap memory.
Q2. What happens if free() is not used?
Memory leak occurs.
Q3. Which initializes memory to zero?
calloc().
Q4. Can realloc increase memory size?
Yes.
Q5. Is dynamic memory automatically freed?
No, programmer must free it.