Porcospino Puzzolente
Porcospino Puzzolente

Reputation: 41

Recursive realloc() throw "invalid next size" after the 7th cicle

So, I have a pointer which need to increase it's "length" until the user insert a negative number or "e". It starts with the length of "1", via a malloc() then I use into a do{...} while(...) loop the realloc() function to increase its lenght. Here's the code:

int *array = malloc (sizeof(int) * 1);
bool exit = false;
int lastIndex = 0, value;

do {
    printf ("Insert a positive number. Insert a negative number or \"e\" to exit:  ");

    int scanf_result = scanf("%i", &value);
    if (scanf_result) {
      if (value >= 0) {
        array[lastIndex] = value;
        lastIndex++;
        array = (int*) realloc (array, lastIndex * sizeof(int));
      } else {
        exit = true;
      }
    } else {
      exit = true;
    }
} while (!exit);

I can't figure out why after the 7th cicle it exit with the error realloc(): invalid next size.

Any idea? Thanks in advice for help.

Upvotes: 2

Views: 63

Answers (2)

dbush
dbush

Reputation: 223699

You're not reallocating enough memory:

array = (int*) realloc (array, lastIndex * sizeof(int));

On the first iteration of the loop, lastIndex is incremented from 0 to 1, then you run the above realloc call. Since lastIndex is 1, you still only have enough space for 1 element. As a result, you write past the end of allocated memory on the next iteration.

This invokes undefined behavior, which in your case manifests as appearing to work properly for the first 6 iterations and failing on the 7th. It could have just as easily crashed on the first or second iteration.

Add one to the size you're allocating:

array = realloc(array, (lastIndex + 1) * sizeof(int));

Also, don't cast the return value of malloc/realloc.

Upvotes: 3

grapes
grapes

Reputation: 8636

Fix your realloc:

array = (int*) realloc (array, (lastIndex + 1) * sizeof(int))

You are allocating one item less than you need to.

Upvotes: 0

Related Questions