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.
int*int *a = malloc(sizeof *a);This results in an unrecoverable memory leak