Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c realloc(): invalid next size

I get this error and searching online hasn't solved it so, here's my code^^:

void addSoggetto(char* s)
{
    soggetti_length++;
    if(realloc(soggetti, soggetti_length*sizeof(int))==NULL) 
    {
        printf("Realloc Failed");
        return;
    }

Basically I have an array of pointers (soggetti) and its length (soggetti_length). Every time this function is ran, I realloc the size to make place for another pointer. Problem is, exactly the fifth time the function is called, I get:

realloc(): invalid next size

Do you know how can I do? I think I can exclude that the memory I realloc is not enough, I tried to increase it and nothing changes. Oh, and I debugged it with gdb, the function crashes BEFORE returning, so I don't even get something like a NULL return.

like image 804
Ryno Avatar asked Mar 16 '26 12:03

Ryno


1 Answers

Read the manpage for realloc(). realloc() returns a pointer to the new allocation, it does not change the old pointer you passed as an argument. (It can't, because C uses pass by value, not pass by reference). So the

if(realloc(soggetti, soggetti_length*sizeof(int))==NULL) 

is a memory leak (and wrong). You need something like:

if(sogetti = realloc(soggetti, soggetti_length*sizeof(int))) 

but in this case, an allocation failure will also leak memory. So, to be safe, you can do:

void *newpointer;
if(newpointer = realloc(soggetti, soggetti_length*sizeof(int)))
    {
        sogetti = newpointer;
    }
else
    {
        //handle out-of-memory
    }

With the rest of your code, we can see the other problem:

Soggetto* new = malloc(sizeof(Soggetto));
...
soggetti[soggetti_length-1]= new;

You've allocated an int worth of memory (sizeof(int)) per sogetto_length, but you are storing a 64-bit Sogetto *. This thrashes the heap by overwriting its metadata in memory (hence the invalid next size, the size part of a heap data structure was overwritten).

Write

void *newpointer;
if(newpointer = realloc(soggetti, soggetti_length*sizeof(Sogetto *))) //here!
    {
        sogetti = newpointer;
    }
else
    {
        //handle out-of-memory
    }

To handle this correctly. To find such bugs, I'd recommend valgrind, address sanitizer.