Kosmo零
Kosmo零

Reputation: 4151

Does c++ realloc function applies delete operation for old data block if moving data to different block?

The function may move the memory block to a new location, in which case the new location is returned.
For example I have a pointer to an array:

int *arr; // somewhere next it initialized, filled with elements and etc

Somewhere I need to:

void* location = realloc(arr, NEW_SIZE);

What will happen with old memory block place?

If realloc return pointer that not math to arr, should i use next code?:

delete arr;
arr = (int*)location;

Upvotes: 1

Views: 2125

Answers (4)

dmitrycello
dmitrycello

Reputation: 184

What will happen with old memory block place?

This question was not yet answered. The answer is simple, it is easy to check in your code. When realloc returns the same address (usually if you reduce the block size), calling free with old address produce no error, which is true since it is also a new address. When it returns different address, calling free with old address fails.

So, it does free the old block when it is reallocated:

void* location = realloc(arr, NEW_SIZE);
// do not free arr, it points to the same or already freed block

Upvotes: 2

LihO
LihO

Reputation: 42123

realloc(void *ptr, size_t new_size) requires the given area of memory that ptr points to to be previously allocated by malloc(), calloc() or realloc() and not yet freed with free(), otherwise, the results are undefined.

Use realloc only with malloc, calloc or another realloc and clean it up with free.
In C++ use always new with delete and new[] with delete[].

Upvotes: 6

Component 10
Component 10

Reputation: 10497

Rule #1: dont mix new/delete with malloc/free.

If you're allocating with malloc() in the first place and you need a bigger heap space then you need to call realloc() which will return you a new pointer which may not map to the same memory areas as arr therefore you should not use it.

Free malloc'ed/realloc'ed space with free

Upvotes: 5

Lindydancer
Lindydancer

Reputation: 26134

The function realloc is inherited from good old C. It does not run destructors or do any other C++ magic. It can also only be applied to blocks allocated using malloc (and friends) -- it can not be used for blocks allocated using 'new'.

Upvotes: 8

Related Questions