#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    3

    What happens when realloc fails?


    what happens if realloc fails to allocate new memory?
    does it return NULL?
    if so, can i lose data?
    for example, consider the following code:

    Code:
    int main()
    {
       char *str;
    
       /* Initial memory allocation */
       str = (char *) malloc(8);
       strcpy(str, "example");
       printf("String = %s,  Address = %u\n", str, str);
    
       /* Reallocating memory */ 
       str = (char *) realloc(str, 5);
       strcat(str, ".com");
       printf("String = %s,  Address = %u\n", str, str);
    
       free(str);
       
       return(0);
    }
    (it's not my code, i found it on the internet)

    now lets say realloc fails and returns NULL, does it mean i'll lose the address of "example" for good?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    Yes, that code is broken (twice).

    First mistake is that the realloc size is new new total size, not the amount you want to add to the old size. So realloc'ing down to 5 bytes would be completely wrong.

    The other problem is detecting and handling the error case.
    What you should do is this.
    Code:
    void *temp = realloc(str, 12);
    if ( temp != NULL ) {
       str = temp;
       strcat(str, ".com");
    } else {
       // no more memory:
       // str is still valid, so do something with it
       // if this were an editor say, you might try to save a recovery file.
       free( str );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    3
    thank you so much, salem.

IMN logo majestic logo threadwatch logo seochat tools logo