Search code examples
cmallocrealloc

using realloc in C with malloc


I somewhat understand what realloc does but when trying to reallocate a certain size of memory doesn't seem to click in to my mind. What if there is not a contigious size of the size wanted. Or if null is passed in as the pointer or if the size passsed in was 0. I know that if the size is 0 then it wants to free that memory. Question: using malloc with realloc?

void *realloc(void *ptr, size_t newsize)
{
  if(newsize == 0)
    free(ptr);
  if(ptr == NULL)
    //does something
  //how does it malloc a size and copy everything over?
}

Solution

  • if (newsize == 0) {
        free(ptr);
        return;
    }
    if (ptr == NULL)
        return malloc(size);
    
    // otherwise do a true realloc
    

    As for

    What if there is not a contigious size of the size wanted.

    Then realloc returns NULL and sets errno to indicate the error.