1

So lets say I have a chunk of bytes allocated with new and the size is not enough anymore. I would like to add another bunch of bytes to it without having to reallocate and copy over all the existing data.

I realize that there is no way to guarantee that this is possible since the memory right after my allocated chunk might be occupied but in theory, it should be possible to 'try', right? I'm thinking this could slightly optimize the performance of my dynamically sized container.

user81993
  • 6,167
  • 6
  • 32
  • 64
  • 2
    Not an exact duplicate, but possibly interesting: http://stackoverflow.com/questions/3482941/how-do-you-realloc-in-c. also http://stackoverflow.com/questions/16714937/what-is-c-version-of-realloc-to-allocate-the-new-buffer-and-copy-the-conten . You are asking a slightly different question though since you don't want the address to change - sadly the anser is the same. – John3136 Jun 29 '16 at 06:12
  • That's exactly what std::realloc does! – Serge Ballesta Jun 29 '16 at 08:59

2 Answers2

2

As stated in the comment, it is not possible with standard C++.

But as your goal is to reduce the number of reallocate and copy operations, you can achieve it by allocating memory in advance:

If your container is full and you want to add another element, don't just increase the capacity by one, instead increase it by say, 25% or 50%. This will reduce the number of reallocate and copy operations from O(n) to O(log(n)) when adding single elements to your container. Of course this advantage comes at the cost of additional memory being allocated. However your original suggestion also relies on free memory being available, so there is not really a difference.

A similar strategy seems to be used by common implementations of std::vector.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
0

The function std::realloc may help you.

The reallocation is done by either:

a) expanding or contracting the existing area pointed to by ptr, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined.

b) allocating a new memory block of size new_size bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block.

See also cppreference

Community
  • 1
  • 1
Null
  • 657
  • 2
  • 6
  • 15