Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 behaviour 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?

like image 663
Ant Avatar asked Oct 19 '08 13:10

Ant


People also ask

What does realloc () function do?

In the C Programming Language, the realloc function is used to resize a block of memory that was previously allocated. The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

What is the difference between realloc () and free?

Well, realloc may change the size of the block in place, or allocate a new one and copy as much as will fit. In contrast, malloc and free together can only allocate a new one, and you have to do your own copying.

Does realloc initialize memory?

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized.

Do you need to free with realloc?

In short, no. Once you call realloc() , you do not have to free() the memory addressed by pointer passed to realloc() - you have to free() the memory addressed by the pointer realloc() returns.


1 Answers

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
like image 181
Rômulo Ceccon Avatar answered Oct 25 '22 11:10

Rômulo Ceccon