Home > database >  Confusion about using malloc/calloc pointer to hold the return value of realloc
Confusion about using malloc/calloc pointer to hold the return value of realloc

Time:12-16

Someone said that using the original malloc()/calloc() pointer as the variable that holds the return value of realloc() is wrong. Here is an example:

#include <stdlib.h>


int main()
{
    int *malloc_ptr = malloc(5 * sizeof(int));
    malloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));


    return 0;
}

Their reasoning was that if realloc() failed it would return NULL thus making malloc_ptr == NULL. That would make you lose access to the memory you requested with malloc(). Their solution was to do this:

#include <stdlib.h>


int main()
{
    int *malloc_ptr = malloc(5 * sizeof(int));
    int *realloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));

    if (realloc_ptr == NULL) {
        // Whatever you want to do
    } else
        malloc_ptr = realloc_ptr;


    return 0;
}

However if they are correct doesn't that mean that some software that uses the malloc pointer as the holder of realloc() could be incorrect because I've seen a lot of people use the malloc()/calloc() pointer as the variable that holds the return value of realloc(). Is this true?

CodePudding user response:

As per man realloc, this would be correct way of realloc handling:

#include <stdlib.h>

int main()
{
    int *malloc_ptr = malloc(5 * sizeof(int));

    if (malloc_ptr == NULL) {
        fprintf(stderr, "Could not allocate memory\n");
        /* here goes error handling */
    }

    /* ... */

    int *realloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));

    if (realloc_ptr == NULL) {
        fprintf(stderr, "Could not reallocate memory, keeping the old allocated block\n");
        /* here goes error handling */
    } else {
        malloc_ptr = realloc_ptr;
    }

    /* ... */

    free(malloc_ptr);

    return 0;
}
  • Related