Dynamic Memory Allocation in C (malloc, calloc)
Dynamic Memory Allocation allows a program to request memory while execution is running.
This makes programs flexible when handling unknown or varying amounts of data.
What is Dynamic Memory?
In static memory allocation, memory size is fixed during compile time. Dynamic memory allocation allows you to allocate and release memory at runtime.
- Flexible memory usage
- Memory allocated from Heap
- Used when data size is unknown
- Different from stack memory
Functions Used for Dynamic Memory
- malloc() β allocate memory block
- calloc() β allocate multiple blocks & initialize with 0
- realloc() β resize memory
- free() β release memory
malloc()
malloc() stands for "Memory Allocation". It allocates a block of memory and returns a void pointer.
ptr = (int*) malloc(size_in_bytes);
- Does not initialize memory β contains garbage
- Returns NULL if allocation fails
calloc()
calloc() stands for βContiguous Allocationβ. It allocates multiple memory blocks and initializes all bytes with 0.
ptr = (int*) calloc(number_of_elements, size_of_each);
- Always initializes memory with zero
- Useful for arrays
Difference Between malloc() and calloc()
- malloc() β uninitialized memory
- calloc() β initialized with 0
- calloc() requires two arguments
- malloc() requires one argument
- calloc() is slower due to initialization
Memory Allocation Flow
- Program requests memory β Heap
- Pointer stores the starting address
- When not needed β free() releases memory
5 Practical Examples of malloc() & calloc()
Example 1 β malloc() for Integer Array
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = (int*) malloc(5 * sizeof(int));
for(int i=0; i<5; i++)
p[i] = i + 1;
for(int i=0; i<5; i++)
printf("%d ", p[i]);
free(p);
return 0;
}
Example 2 β calloc() Initialize with Zero
#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]); // prints 0
free(p);
return 0;
}
Example 3 β malloc() for Float
#include <stdio.h>
#include <stdlib.h>
int main(){
float *p = (float*) malloc(3 * sizeof(float));
p[0] = 2.5;
p[1] = 3.7;
p[2] = 4.8;
for(int i=0; i<3; i++)
printf("%.1f ", p[i]);
free(p);
return 0;
}
Example 4 β calloc() for String Storage
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *name = (char*) calloc(20, sizeof(char));
strcpy(name, "Sourav Sahu");
printf("%s", name);
free(name);
return 0;
}
Example 5 β malloc() and free() Demonstration
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = (int*) malloc(sizeof(int));
*p = 100;
printf("Value = %d\n", *p);
free(p);
return 0;
}
Practice Questions
- What is dynamic memory allocation?
- Explain malloc() and calloc() with differences.
- Why is free() important?
- What is the meaning of heap memory?
- Write advantages of dynamic memory.
Practice Task
Write a C program using malloc() to store 10 integers,
find the largest number, and free the allocated memory.