Search code examples
c++cmemoryvectorrealloc

Preformance of realloc


Looks like realloc doesn't free old memory (on success or failure), while vector always delete old memory and allocate a new block.

Can I say for POD data, realloc has better performance than vector?

For example:

int *p = malloc(5 * sizeof(int));
...
int *new_p = (int*) realloc(p, 10 * sizeof(int));

Will the old memory p be freed here?


Solution

  • Realloc may expand the actual allocation (if possible) or may allocate a new chunk, copy the old chunk values and free the old chunk. In the first case it has better performance, but, as you don't know in advance what it's going to do, you must suppose that pointers to the old chunk will become invalid.