Search code examples
cmemory-management

Determining realloc() behaviour before calling it


As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things:

if free contiguous block exists
    grow current block
else if sufficient memory
    allocate new memory
    copy old memory to new
    free old memory
else
    return null

Growing the current block is a very cheap operation, so this is behavior I'd like to take advantage of. However, if I'm reallocating memory because I want to (for example) insert a char at the start of an existing string, I don't want realloc() to copy the memory. I'll end up copying the entire string with realloc(), then copying it again manually to free up the first array element.

Is it possible to determine what realloc() will do? If so, is it possible to achieve in a cross-platform way?


Solution

  • realloc()'s behavior is likely dependent on its specific implementation. And basing your code on that would be a terrible hack which, to say the least, violates encapsulation.

    A better solution for your specific example is:

    1. Find the size of the current buffer
      • Allocate a new buffer (with malloc()), greater than the previous one
      • Copy the prefix you want to the new buffer
      • Copy the string in the previous buffer to the new buffer, starting after the prefix
      • Release the previous buffer