0

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;
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Kosmo零
  • 4,001
  • 9
  • 45
  • 88

3 Answers3

7

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'.

Lindydancer
  • 25,428
  • 4
  • 49
  • 68
  • oh so... thanks for clearing this things out for me. i didn't even test my application for run-ability, because run into that question – Kosmo零 May 18 '12 at 08:06
4

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

Component 10
  • 10,247
  • 7
  • 47
  • 64
3

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[].

LihO
  • 41,190
  • 11
  • 99
  • 167