Search code examples
cdynamic-memory-allocationrealloc

What would realloc do if there is no sequential space of memory?


realloc is used to reallocate the memory dynamically.

Suppose I have allocated 7 bytes using the malloc function and now I want to extend it to 30 bytes.

What will happen in the background if there is no sequential (continously in a single row) space of 30 bytes in the memory?

Is there any error or will memory be allocated in parts?


Solution

  • realloc works behind the scenes roughly like this:

    • If there is enough free space behind the current block to fulfill the request, extend the current block and return a pointer to the beginning of the block.
    • Else if there is a large enough free block elsewhere, then allocate that block, copy the data from the old block over, free the old block and return a pointer to the beginning of the new block
    • Else report failure by returning NULL.

    So, you can test for failure by testing for NULL, but be aware that you don't overwrite the old pointer too early:

    int* p = malloc(x);
    /* ... */
    p = realloc(p, y); /* WRONG: Old pointer lost if realloc fails: memory leak! */
    /* Correct way: */
    {
      int* temp = realloc(p, y);
      if (NULL == temp)
      {
        /* Handle error; p is still valid */
      }
      else
      {
        /* p now possibly points to deallocated memory. Overwrite it with the pointer
           to the new block, to start using that */
        p = temp;
      }
    }