0

Stated that there is no C++ equivalent of the C realloc function, I've found in another question that such a thing is automatically managed by std::vector and we should use it instead. I'm fine with it. I guess that, since there is no other way of do reallocation, the std::vector will just call realloc for me.

However, the question is: if I'm overriding the new and the delete operators for managing of tracking memory usage globally, they will not be called in the case someone calls old C functions (malloc, calloc, realloc, free).

How can it be done? Is it correct that std::vector replaces realloc?

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64

1 Answers1

3

std::vector won't call realloc; it will use its allocator to achieve something similar: allocating new memory, moving objects into it, then deallocating the old memory. The default allocator uses operator new and operator delete, and so will use your replacements if you provide them.

realloc would be entirely the wrong thing to do if the vector contains non-trivial objects; it copies raw data, while C++ objects generally have to be copied or moved by calling their special functions.

Nothing in the C++ library (except perhaps the default implementations of operator new and operator delete) will call the C allocation functions directly. Since you shouldn't be calling them yourself, you only need to worry about them if you're using a C library.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • If you are using C libraries that call malloc family functions, many implementation allow you to either hook or replace the malloc with your own. You can use this mechanism to track memory allocations. And as mentioned above many C++ implementation use malloc and free as the default implementations of new and delete. – doron Mar 09 '15 at 11:50
  • It would be nice for a version of `realloc` that returns false and doesn't do anything if the request was unsuccessful. – Neil Kirk Mar 09 '15 at 11:50
  • @NeilKirk: From what I understand, this is unlikely to be helpful with todays multi-threaded allocators. Even if the old and new size allocation both could be satisfied from the same heap range (certainly not a given), it's still unlikely that there's sufficient memory available. – MSalters Mar 09 '15 at 12:00