


However, if you absolutely need the general efficiency of realloc, and if you have to accept new for the original allocation, then your only recourse for efficiency is to use compiler-specific means, knowledge that realloc is safe with this compiler. Int* mydata = (int*)realloc(data,6*sizeof(int)) Instead of the presented code int* data = new int The C++ containers suffer from being designed in a way that excludes use of realloc.

The closest is the automatic reallocation of (the internal buffers of) containers like std::vector. And in practice it's just needlessly risky.Ĭ++ does not offer functionality corresponding to realloc. It's likely but by no means guaranteed that C++ new and C malloc use the same underlying allocator, in which case realloc could work for both. That's because the underlying data structures that keep track of free and used areas of memory, can be quite different. You can only realloc that which has been allocated via malloc (or family, like calloc).
