I have some problems using realloc()
, so I made a sample program to illustrate the problem using as less code as possible.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
unsigned int i;
unsigned long long *a;
srand(time(NULL));
a = malloc(sizeof(unsigned long long));
for (i = 0; i < 20; ++i)
{
a[i] = rand() % 32;
printf("%llu\n", a[i]);
a = realloc(a, (i + 1) * sizeof(unsigned long long));
}
return 0;
}
This outputs:
* glibc detected demo: realloc(): invalid next size: 0x0000000000dc3010 **
Why does this crash?
Edit:
I tried chaning (i + 1)
to (i + 2)
and then the program worked, but I do not understand why. I only request to extend the memory space by one unsigned long long
.
The first time your loop runs, i
is equal to 0
. You realloc a
to hold i + 1
elements, which is... 1
!
The second time your loop runs, you try to write to a[i]
with i == 1
, which is the second element of your array. But since your array can only hold 1
element, that can cause a crash.