Search code examples
cstructrealloc

C - realloc error when changing member in struct


I get this error when trying to change an int member in a struct:

Error in `./resize': realloc(): invalid next size: 0x00000000006bc010 *** Aborted (core dumped)

My code is:

#include <stdlib.h>

typedef struct {
    char* name;
    int size;
} fich;

int main(){

    int i = 1;
    fich * ptr = NULL;

    while(i < 5){
         fich* newptr = realloc(ptr, i * sizeof(fich));
         if(newptr != NULL)
             ptr = newptr;
         else return 1;

         ptr[i].name = "stufs";
         ptr[i].size = 1;

         i++;
    }

return 0;
}

I can change name just fine, but not size. What's going on?


Solution

  • In C, arrays start at index 0. Your first iteration with i=1 allocates space for one fich, which is ptr[0], not ptr[1].

    Classic off-by-one in combination with buffer-overflow :-)