cmemory-managementrealloc

How does realloc handle memory insufficiency?


If there is not enough memory available at the original location:

  • Does it allocate multiple memory blocks and return a pointer pointing to one of those, with all blocks being internally linked with each other?
  • Does the original region get copied into a new location where enough memory is available?
  • Is a pointer to the new address returned, while the memory at the old location is freed?

Is realloc compiler/OS dependent?


Solution

  • realloc attempts to extend your available memory range if sufficient memory is available behind it on the heap. If not then it is equivalent to malloc a block of the new size, memcpy your contents there, free the old block. This is independent of both OS and compiler and depends on the implementation of libc that you link against.

    On a similar note: mremap/MREMAP_MAYMOVE (available on modern Linux) will attempt to extend your virtual mapping by the requested size. If that is not possible then it will move your mapping to a new virtual address that has sufficient VM space behind it and then extend your mapping. This is very fast if you are frequently resizing large mappings since no physical copying is done.