Results 1 to 1 of 1

Thread: C: what happens with memory if stdlib realloc fails...

  1. #1
    Join Date
    Aug 2005
    Location
    Sweden
    Beans
    407

    Question SOLVED C: what happens with memory if stdlib realloc fails?

    Reference: http://www.cplusplus.com/ref/cstdlib/realloc.html

    If realloc fails a null pointer will be returned, but is the original memory chunk freed?
    In other words is it safe to do this?:
    Code:
    int* pointer;
    pointer=alloc(sizeof(int)*10);
    pointer=realloc(sizeof(int)*100);
    free(pointer);
    Or do I have to do this to be sure to avoid memory leaks?:
    Code:
    int* pointer;
    int* ptmp;
    pointer=alloc(sizeof(int)*10);
    ptmp=realloc(sizeof(int)*100);
    if (ptmp!=0) {
        pointer=ptmp;
    }
    else {
        free(pointer); //<------ free the original memory
        //Other error handling
    }

    EDIT:
    see: http://www.c-faq.com/malloc/realloc.html
    Last edited by red_Marvin; August 9th, 2006 at 12:21 AM. Reason: Question solved.
    Don't peach linux. Melon it!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •