Search code examples
clinuxpointersfreerealloc

Should I free() the temporary pointer used to store the result of a realloc()?


So this is on x86 machine running a Debian based Linux OS. I have the following function which is called a lot of times. I am not sure if I should free() the temp pointer or I can just let the function as it is.

int my_function (char *Data, int Data_size) {

    void *temp;
    Data_size = 7000;

    // Allocate a huge array to store a line of the datalogger
    //
    temp = (char *) realloc( Data, Data_size);
    if (temp == NULL)
    {
        printf("Reallocate Data ERROR\n");
        free(Data);
        return -1;
    }
    Data = temp;

    // Do something with the Data

    return 1;
}

Solution

  • Since you use realloc (not simply malloc) it looks like Data has already been allocated somewhere else, presumably in the function that calls my_function. To clear any misconception upfront, the Data = temp; assignment will not pass the updated value of temp obtained from realloc back to the caller, since char *Data is passed by value.

    Now onto the actual question. Does the caller expect my_function to free the Data buffer or not? The code appears to be free'ing it if realloc fails. If so, it should probably also free(temp); if realloc succeeds.


    [ EDIT ] To emphasize the point @mksteve made in a comment, once realloc succeeds in my_function the temp pointer is no longer necessarily equal to the original Data, and the original Data pointer is no longer eligible to be free'd since it may point to deallocated data at that point. Since the reallocated temp pointer is not passed back to the calling function, it would be illegal for the caller to attempt to free(Data) after my_function returns.

    On a general note, it's always safer to free things at the same level where they were (re)allocated to begin with. Relying on the caller to allocate and the callee to dispose is risky business for more reasons than just this example.