1

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.

3
  • "an array of pointers to an arbitrary type" hmmm... then why are you using int* Commented Oct 20, 2021 at 13:52
  • @4386427 Because this is an example. Commented Oct 20, 2021 at 15:46
  • regarding: int *a = malloc(sizeof *a); This results in an unrecoverable memory leak Commented Oct 21, 2021 at 20:45

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Well, at least one problem is that you're allocating size bytes instead of elements.

data = realloc(data, ++size * sizeof *data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.