Best way to increase heap buffer size

Viewed 327

I have allocated a buffer in heap with malloc, and then I want to increase that buffer.

I don't need anymore the data in the buffer, only want to increase the size.

What is the best way? realloc or free and malloc?

3 Answers

free() and malloc() is probably better, because realloc() had to copy the data if not enough room is available in the same place, which is an unnecessary job then.

Use free() and then malloc(). The realloc() function will try to increase the size of the allocated memory in place, but will move your data to the new location if neccessary. Since you no longer need the data, this copying is a waste of time.

This is close to low level optimization. Long story made short: it depends. If you only allocate rather large size buffers, free + malloc could be nicer because you avoid the copy of the old data. But if you allocate tiny buffers, alloc could allocate more than requested. In that case, realloc would be faster because it would be a plain no-op.

Related