beardeadclown
beardeadclown

Reputation: 377

realloc( ): Invalid next size

Minimal reproducible example:

prog.c

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  size_t bufsiz = 4, tmp;
  char *buffer;

  for (buffer = malloc(bufsiz), tmp = 0; buffer[tmp] = fgetc(stdin); ++tmp) {
    if (bufsiz == tmp && !realloc(buffer, bufsiz *= 2))
      return 1;
} }

Compile and run

gcc prog.c -o prog

echo duck | ./prog
realloc(): Invalid next size
Aborted

I have read many similar threads but could not find the solution.

Upvotes: 0

Views: 5250

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222714

realloc returns a pointer to the allocated space, which may be equal to the previous pointer or may be a new value or a null pointer. You cannot simply call realloc(buffer, bufsiz *= 2); you must use the return value as the new address.

When realloc returns a new value, the previous memory is no longer allocated and should not be used.

You will also need a different stopping condition for the loop. Using buffer[tmp] = fgetc(stdin) as the test will cause it to stop when a null character is read, but you should not expect a null character to mark the end of the input. fgetc will return EOF when the end of input is reached, but EOF is generally not representable as a char value. You must store (in an int) and test the return value of fgetc before assigning it to a char.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

For starters this assignment

buffer[tmp] = fgetc(stdin)

can result in accessing the memory outside the array.

For example let's assume that initially bufsiz is equal to 1.

So after the first iteration of the loop the variable tmp will be equal to 1 due to the expression ++tmp in the loop statement. And in the condition of the loop there will be

buffer[1] = fgetc(stdin)

However 1 is not a valid index in this case.

And moreover the user can interrupt the input. In this case the function fgetc will return EOF that you will try to store in the character array.

The second problem is that in this expression

!realloc(buffer, bufsiz *= 2)

the returned value of the function realloc that is the address of the new allocated memory is lost. So the pointer buffer will be invalid.

The loop is not readable. It is a law in programming that a non-readable code contains a bug.

Make the code more simpler and more readable.

Upvotes: 1

Related Questions