std::string is contiguous

You can safely assume that the memory buffer used by std::string is contiguous. Specifically, the address of the string’s first character can be used as the address for the whole string, just like a C-style char array:

std::string str = "foo";
strncpy(&str[0], "bar", 3); // str now contains "bar".

Why is this safe? The current C++ standard apparently doesn’t guarantee that the string is stored contiguously, but it is in all known implementations. Additionally, the next C++ standard (C++0x) will make this guarantee. So the above usage is valid on all present and future C++ implementations.

Why is this important? It’s common for functions, especially in the Windows API, to “return” strings by copying them into a buffer passed to the function. Since the memory buffer used in std::string is contiguous you can safely pass it to the function, after resizing the string to the correct size.

A typical usage for Windows API functions:

// get required buffer size
DWORD bufSize = 0;
GetComputerNameA(NULL, &bufSize);
if (!bufSize && GetLastError() != ERROR_BUFFER_OVERFLOW) {
  throw std::runtime_error("GetComputerNameA failed");
// bufSize now contains required size of buffer, including null terminator
std::string buf(bufSize, '\0');
if (!GetComputerNameA(&buf[0], &bufSize)) {
  throw std::runtime_error("GetComputerNameA failed");
// bufSize now contains actual size of data
// now use buf as a regular std::string

This is cumbersome but actually easier than plain C code, since you don’t have to manage the memory yourself.

Note that the expression &str[0] is valid only if str isn’t empty. Also, everything I’ve said also applies to std::wstring, the wide-character version of std::string.


Post a comment or leave a trackback: Trackback URL.


  • Torkel  On August 13, 2017 at 20:40

    Note: &str[0] is valid when the string is empty in c++11.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: