You can only realloc
that which has been allocated via malloc
(or family, like calloc
).
That's because the underlying data structures that keep track of free and used areas of memory, can be quite different.
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. But formally that's in UB-land. And in practice it's just needlessly risky.
C++ does not offer functionality corresponding to realloc
.
The closest is the automatic reallocation of (the internal buffers of) containers like std::vector
.
The C++ containers suffer from being designed in a way that excludes use of realloc
.
Instead of the presented code
int* data = new int[3];
//...
int* mydata = (int*)realloc(data,6*sizeof(int));
… do this:
vector<int> data( 3 );
//...
data.resize( 6 );
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.
Otherwise, if you absolutely need the general efficiency of realloc
but is not forced to accept new
, then you can use malloc
and realloc
. Using smart pointers then lets you get much of the same safety as with C++ containers.
vector
. – Scuppermalloc
(few microseconds) vs.std::vector
(~200 millisecond!).std::vector
is not a magic solution to every memory problem – Oratorint* n = new int[200 * 1024 * 1024]{};
gives about the same performance on MSVC. – Elynstd::vector
is less performant thannew
, I compared it tomalloc
, which is a great tool when performance is importance. you can always catch a pointer handed bymalloc
whithunique_ptr
and so, and gain that extra 200 milliseconds that you would never get overstd::vector
ornew[]
do you think it's legit to spend 200 millisecods zeroing bytes on , let's say, a web server? eventually,std::vector
is not an automatic sulotion for C++ reallocations. many developers here said it without thinking twice without even mentioning the side affects. – Orator{}
) is comparable tomalloc
. Additionally, you can use avector
with similar/same efficiency asmalloc
if you usereserve
and e.g.push_back
. – Elynmalloc
you can reallocate, not withnew
, andreserve
zero the bytes as well. – Oratorreserve
does not zero the bytes. You are probably confusing that withresize
. – Elynrealloc
. I mean shouldn't you writeint* mydata = (int*)realloc(data,6*sizeof(int));
– Kropotkin