What is the overhead in the string structure that causes sizeof() to be 32 ?
sizeof(string) tells you the size of the pointer. 4 bytes (You're on a 32-bit machine.) You've allocated no memory yet to hold text.
String Length in C Using the sizeof() OperatorWe can also find the length of a string using the sizeof() Operator in C. The sizeof is a unary operator which returns the size of an entity (variable or value). The value is written with the sizeof operator which returns its size (in bytes).
When we discuss the length of a string, we're usually referring to the number of that string's characters. In C++, string length really represents the number of bytes used to encode the given string. Since one byte in C++ usually maps to one character, this metric mostly means “number of characters,” too.
A variable-length string can contain up to approximately 2 billion (2^31) characters. A fixed-length string can contain 1 to approximately 64 K (2^16) characters.
Most modern std::string
implementations1 save very small strings directly on the stack in a statically sized char
array instead of using dynamic heap storage. This is known as Small (or Short) String Optimisation (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality of reference.
Furthermore, there will be a std::size_t
member to save the strings size and a pointer to the actual char
storage.
How this is specifically implemented differs but something along the following lines works:
template <typename T> struct basic_string { char* begin_; size_t size_; union { size_t capacity_; char sso_buffer[16]; }; };
On typical architectures where sizeof (void*)
= 8, this gives us a total size of 32 bytes.
1 The “big three” (GCC’s libstdc++ since version 5, Clang’s libc++ and MSVC’s implementation) all do it. Others may too.
std::string
typically contains a buffer for the "small string optimization" --- if the string is less than the buffer size then no heap allocation is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With