Search code examples
cmallocdynamic-memory-allocationrealloc

Why do I get a "realloc(): invalid old size" error when executing?


This is the error I get when executing the .exe file built from the code below:

*** Error in `./test_bin.exe': realloc(): invalid old size: 0x00007ffc67d00cf0 ***

I don't understand why realloc() throws an error when I'm using it as intended. I have tried casting before realloc() call, but that doesn't work either.

int main{

    double *test;
    double arr1[5] = {1.0,2.0,3.0,4.0,5.0};
    double arr2[2] = {1.0,2.0};
    int     i;


    test = (double*)malloc(5*sizeof(double));
    test = arr1;
    for(i=0;i<5;i++) printf("%lf ",test[i]);

    printf("\n");

    test = realloc(test,2*sizeof(double));
    test = arr2;
    for(i=0;i<2;i++) printf("%lf ",test[i]);
    printf("\n");
    return 0;

}

Solution

  • From the documentation of realloc (emphasis is mine):

    Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.

    In your case this line:

    test = arr1;
    

    Makes the pointer now point to the array arr1 on the stack. It is not a pointer received from malloc/calloc/realloc and therefore this is undefined behavior (UB).

    Moreover - the chunk of memory you got from malloc (1 line before assigning the pointer to arr1) is now leaked. You cannot have access to it or free it.


    Edit:
    To complete the answer:
    The citation above is somewhat conflicting with the fact that you can use realloc with a NULL pointer. The same documentation link above also mentions further down that-

    If ptr is NULL, the behavior is the same as calling malloc(new_size).

    But anyway this case also does not appy to your code (as the address of array on the stack is not NULL).