Search code examples
crealloc

How to know whether we ran out of memory or it was an error while using realloc()?


realloc(void *ptr, size_t new_size) returns NULL in two cases:

  • If there is not enough memory, the old memory block is not freed and NULL is returned.
  • NULL is also returned if error has occurred.

How do I know what type of problem occurred?

If we are short of memory, I might page some memory to disk.

How do I know whether I should do free(ptr)? (maybe it was already freed by realloc).


Solution

  • Quoting from here

    RETURN VALUE
    
    Upon successful completion with a size not equal to 0, realloc() returns a pointer 
    to the (possibly moved) allocated space. If size is 0, either a null pointer or a 
    unique pointer that can be successfully passed to free() is returned. If there is
    not enough available memory, realloc() returns a null pointer  and sets errno to 
    [ENOMEM].