I am trying to increase the amount of memory I have allocated using malloc. Is there a way to increase the size from 128 bytes to 256 bytes by allocating an additional 128 bytes next to the original block so I can access it as a continuous block of memory?
I am using g++.exe (MinGW.org GCC-6.3.0-1) 6.3.0. Should I use vectors or just get a new allocation and copy over the data with memcpy if the above is not possible?
Vector seems to work and other way is just copying over the to new location. For vector I don't much about how they are implemented but do sometimes they have certain optimization for doing allocating the memory next to the orginal block so copying is not required.
To extend a block allocated using malloc
, one uses realloc
.
realloc
usually extends the block if possible, but it may allocate a new block, copy the data over and deleted the old block. This is unavoidable. Since you never reserved (allocated) the space after the original block, there's no guarantee it's available to extend into.
The only way to guarantee you can extend an 128 byte block into a 256 one is to allocated 256 bytes in the first place.