realloc() & free() in C
The realloc() function is used to resize previously allocated memory.
The free() function is used to release dynamically allocated memory back to the system.
What is realloc()?
realloc() modifies the size of an existing memory block created with malloc() or calloc().
- Can increase or decrease memory
- Keeps old data safe when expanding
- Returns new pointer (may change address)
- Used when exact memory size is unknown
Syntax:
ptr = realloc(ptr, new_size);
What is free()?
free() releases dynamically allocated memory, preventing memory leaks.
- Frees memory created by malloc(), calloc(), realloc()
- After freeing, pointer becomes invalid
- Must call free() after finishing memory usage
free(ptr);
Important Rules
- Never use free() on the same pointer twice
- Always check if realloc() returned NULL
- Do not access memory after freeing
- Use realloc() only on dynamic memory
5 Practical Examples
1. Increase Memory Using realloc()
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = malloc(2 * sizeof(int));
p[0] = 10;
p[1] = 20;
p = realloc(p, 4 * sizeof(int));
p[2] = 30;
p[3] = 40;
for(int i=0;i<4;i++)
printf("%d ", p[i]);
free(p);
return 0;
}
2. Shrink Memory Using realloc()
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = malloc(5 * sizeof(int));
for(int i=0;i<5;i++)
p[i] = i + 1;
p = realloc(p, 2 * sizeof(int));
for(int i=0;i<2;i++)
printf("%d ", p[i]);
free(p);
return 0;
}
3. realloc() Returning NULL
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = malloc(3 * sizeof(int));
int *temp = realloc(p, 100000000000);
if(temp == NULL){
printf("Reallocation failed!");
} else {
p = temp;
}
free(p);
return 0;
}
4. Free Memory After Use
#include <stdio.h>
#include <stdlib.h>
int main(){
char *s = malloc(20);
sprintf(s, "Hello C");
printf("%s", s);
free(s);
return 0;
}
5. realloc() for Dynamic Array Growth
#include <stdio.h>
#include <stdlib.h>
int main(){
int n = 2;
int *arr = malloc(n * sizeof(int));
arr[0] = 5;
arr[1] = 10;
n = 5;
arr = realloc(arr, n * sizeof(int));
arr[2] = 15;
arr[3] = 20;
arr[4] = 25;
for(int i=0;i< n;i++)
printf("%d ", arr[i]);
free(arr);
return 0;
}