🧠 Dynamic Memory Allocation in C
🔹 What is Dynamic Memory Allocation?Dynamic memory allocation is the process of allocating memory at runtime instead of compile time.
- Memory is allocated from the heap
- Useful when data size is unknown at compile time
- Static allocation happens at compile time (fixed-size arrays)
✅ Why Use Dynamic Memory Allocation?
- Handles variable-sized data at runtime
- Efficient use of memory
- Required for linked lists, trees, graphs
- Avoids memory wastage
📌 Header File Required
#include <stdlib.h>
📚 Dynamic Memory Allocation Functions in C
| Function | Purpose | Syntax | Example |
|---|---|---|---|
| malloc() | Allocates memory | ptr = (type*) malloc(size); | int *p = malloc(5*sizeof(int)); |
| calloc() | Allocates & initializes to 0 | ptr = (type*) calloc(n, size); | int *p = calloc(5, sizeof(int)); |
| realloc() | Resizes memory | ptr = realloc(ptr, size); | p = realloc(p, 10*sizeof(int)); |
| free() | Frees memory | free(ptr); | free(p); |
1️⃣ Using malloc()
ptr = (type*) malloc(size_in_bytes);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p;
p = (int*) malloc(5 * sizeof(int));
if(p == NULL) {
printf("Memory allocation failed");
return 1;
}
for(int i = 0; i < 5; i++) {
p[i] = i + 1;
printf("%d ", p[i]);
}
free(p);
return 0;
}
Output: 1 2 3 4 5
2️⃣ Using calloc()
Difference from malloc:
- Initializes memory to 0
- Takes number of elements and size
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int*) calloc(5, sizeof(int));
for(int i = 0; i < 5; i++)
printf("%d ", p[i]);
free(p);
return 0;
}
Output: 0 0 0 0 0
3️⃣ Using realloc()
- Used to resize memory
- Preserves existing data
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int*) malloc(3 * sizeof(int));
for(int i = 0; i < 3; i++) p[i] = i+1;
p = realloc(p, 5 * sizeof(int));
p[3] = 4;
p[4] = 5;
for(int i = 0; i < 5; i++)
printf("%d ", p[i]);
free(p);
return 0;
}
Output: 1 2 3 4 5
4️⃣ Using free()
Used to release dynamically allocated memory.
free(ptr);
ptr = NULL; // avoid dangling pointer
👍 Advantages
- Efficient memory usage
- Allocates memory as needed
- Supports dynamic data structures
👎 Disadvantages
- Manual memory management required
- Memory leaks possible
- Slower than static allocation
📚 FAQs on Dynamic Memory Allocation
Q1. What is dynamic memory allocation?
Memory allocation at runtime from the heap.
Q2. Difference between malloc and calloc?
malloc gives garbage values, calloc initializes memory to 0.
Q3. Can we resize memory?
Yes, using realloc().
Q4. What happens if free() is not used?
Memory leak occurs.
Q5. Is dynamic allocation mandatory?
No, but required for flexible and large data.
🔑 Key Points to Remember
- Heap memory is used for dynamic allocation
- Always check pointer for NULL
- Always free allocated memory
- Use malloc, calloc, realloc wisely