compiled the following code snippet with command: gcc -g -std=c99 src.c
src.c:
#include <stdio.h>
#include <stdlib.h>
void fill(int* arr, int len, int val) {
for (int i = 0; i < len; ++i) arr[i] = val;
}
int main()
{
printf("Hello World\n");
int *p1, *p2;
int *arr1 = malloc (sizeof(int) * 10);
int *arr2 = malloc (sizeof(int) * 10);
printf("BEFORE======================\narr1=%p, arr2=%p\n", arr1,arr2);
fill(arr1, 10, 17);
fill(arr2, 10, 23);
p1 = &arr1[9];
p2 = &arr2[9];
printf("values at addresses %p, %p are respectively: %d, %d\n", p1, p2, *p1, *p2);
arr1 = realloc(arr1, 200);
arr2 = realloc(arr2, 200);
printf("AFTER======================\narr1=%p, arr2=%p\n", arr1,arr2);
fill(arr1, 200, 239);
fill(arr2, 200, 347);
printf("values at addresses %p, %p are respectively: %d, %d\n", p1, p2, *p1, *p2);
p1 = &arr1[99];
p2 = &arr2[99];
printf("values at addresses %p, %p are respectively: %d, %d\n", p1, p2, *p1, *p2);
free(arr2);
free(arr1);
return 0;
}
I was just trying out dynamic memory allocation. To my surprise the free call on arr2
is crashing.
From the memory dump it seems the after reallocation, the arrays are overlapping, which I am not sure why.
The 2nd parameter of realloc
is the size in bytes.
Therefore in these lines:
arr1 = realloc(arr1, 200);
arr2 = realloc(arr2, 200);
You allocate both arr1
and arr2
with 200 bytes, not int
elements.
To fix it change it to:
arr1 = realloc(arr1, sizeof(int) * 200);
arr2 = realloc(arr2, sizeof(int) * 200);
A second issue (as @stark commented) is that in the first instance of this line (right after fill
ing the arrays):
printf("values at addresses %p, %p are respectively: %d, %d\n", p1, p2, *p1, *p2);
p1
and p2
still point to the arrays before reallocation. They are therefore invalid, and derefrencing them causes undefined-behavior.
(The second instance of this line is OK, because p1
and p2
are assigned with the new arrays addresses).