0 day streak
c / intermediate
Snippet

Avoiding Memory Leaks with realloc

When using realloc, always use a temporary pointer. If realloc fails, it returns NULL but the original memory remains allocated.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdlib.h>
#include <stdio.h>
int main() {
int *arr = malloc(2 * sizeof(int));
if (!arr) return 1;
int *temp = realloc(arr, 10 * sizeof(int));
if (!temp) {
free(arr);
return 1;
}
arr = temp;
free(arr);
return 0;
}
Breakdown
1
int *temp = realloc(arr, ...);
Store result in temp to prevent losing the original address on failure.
2
if (!temp) { free(arr); }
Explicitly free the original buffer if the expansion fails.