Search code examples
c++stringpointersheap-memoryinvalidation

Can std::string reallocation invalidate pointer to heap?


My question is regarding the following scenario:

std::string *ps = new std::string();
*ps = aVeryLargeString;

What usually happens from my experience is that aVeryLargeString exceeds the capacity of *ps, so *ps allocates extra memory, keeping the starting position the same. So ps will still point to the new string as the location in memory is the same.

However, what happens if there is not enough contiguous space at that memory location? Does the reallocation move the string to a completely different place, thus invalidating the pointer?


Solution

  • What usually happens from my experience is that aVeryLargeString exceeds the capacity of *ps, so *ps allocates extra memory, keeping the starting position the same.

    No, this is not generally true. When you exceed the capacity, the string uses its allocator to allocate a completely different block (with size some factor of the previous capacity), and copies the characters over. Unless you keep a pointer or reference to the actual characters of the string (e.g. via &(*ps)[0], or ps->c_str()), as opposed to a pointer to the string object itself (which is what ps is), you don't have to worry about this.

    So ps will still point to the new string as the location in memory is the same.

    ps is not, and cannot be, affected in any way by an operation on the string it points to (*ps) (obviously excluding operations which exhibit undefined behavior, which can have any effect whatsoever).