Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading