new[]
doesn't support change the size of allocated memory, does it?
For example, I allocated memory with new[]
for buffer (array of char) and I want to get the additional memory.
Should I use malloc
/realloc
instead in this case?
new[]
doesn't support change the size of allocated memory, does it?
For example, I allocated memory with new[]
for buffer (array of char) and I want to get the additional memory.
Should I use malloc
/realloc
instead in this case?
new
does not support that.
You can mimic the behavior of realloc
manually using new
, delete
and memcpy
.
By the way, you should always use the same family of methods i.e. either malloc
/ realloc
/ free
or new
/ delete
, and not mix realloc
with new
/ delete
. See for example the FMM errors reported by Purify.
The closest you can come in standard C++ without resorting to the C holdovers malloc
and realloc
is to use std::vector<char>
. This can be resized at any time, and if the underlying storage gets reallocated the contents will be automatically copied.
It is not a good idea to use malloc/realloc with new.
new will not support reallocating more memory once applied.
So a good idea would be to create a new buffer with extra memory, memcpy and delete the old buffer. Then point to this new buffer.