I want to create and resize an array of pointers to an arbitrary type. But for some reason, this crashes in the fifth iteration:
#include <stdlib.h>
#include <stdio.h>
int main() {
int **data = NULL;
size_t size = 0;
for (size_t i = 0; i < 10; i) {
printf("begin iteration #%lu...\n", i 1);
int *a = malloc(sizeof *a);
data = realloc(data, size);
data[size - 1] = a;
}
}
The output is:
begin iteration #1...
begin iteration #2...
begin iteration #3...
begin iteration #4...
begin iteration #5...
realloc(): invalid next size
Aborted (core dumped)
I know there are already houndreds of questions regarding realloc(): invalid next size
and I looked through many of them but I still wasn't able to figure it out. I am pretty sure I am missing something fairly basic here.
CodePudding user response:
You're not allocating enough space:
data = realloc(data, size);
This is telling realloc
to allocate size
bytes, so 1 byte on the first interation, 2 on the second, etc. This is not enough to hold what you want to store, so you're writing past the end of allocated memory, triggering undefined behavior.
You need to multiply this value by the element size.
data = realloc(data, size * sizeof *data);
Also, you're using the wrong format specifier here:
printf("begin iteration #%lu...\n", i 1);
For a size_t
, the size modifier is z
:
printf("begin iteration #%zu...\n", i 1);
CodePudding user response:
Well, at least one problem is that you're allocating size
bytes instead of elements.
data = realloc(data, size * sizeof *data);