Reputation: 3756
In the following C++ code, where is s allocated? Does it use heap, data, bss, or some combination? I'm on a Linux/x86 platform in case that makes a difference. Is there a way to have the g++ compiler show me the layout?
#include <string>
#include <iostream>
using namespace std;
string s;
int main()
{
s = "test";
cout << s;
}
Upvotes: 3
Views: 1887
Reputation: 106096
The C++ Standard doesn't define where the compiler puts such objects, but on UNIX it's reasonable to think that the string data would be either:
Given the implementation and members of std::string aren't defined, it's not generally clear whether any members should end up being non-0 after default initialisation, that's why there are so many possibilities.
Compiling on Linux with GCC and no optimisation, then inspecting the executable with "nm -C", I happen to have 's' on the BSS.
~/dev nm -C bss | grep ' s$'
08048896 t global constructors keyed to s
08049c98 B s
man nm
...
"B" The symbol is in the uninitialized data section (known as
BSS).
While static string objects are never on the heap, one or more pointers they contain may end up pointing at memory on the heap if the string is assigned text too large for any (optional) internal buffer. Again, there's no specific rule to say they won't allocate heap memory for other purposes, or pre-allocate heap for textual content even while still empty (but that would be pretty silly).
Upvotes: 2
Reputation: 6961
The string 'object' would be in the data segment.
But it will have some dynamic allocations (for holding the actual string characters, for example) on the heap.
EDIT: As correctly commented, a 'string' doesn't HAVE to use dynamic allocations. For example, if the string is short, it may be kept internally. This is implementation dependent.
You can examine the address of the object itself and of pointers it contains to see where things are. If you know the memory mapping of your specific executable, you can tell what lives where.
Upvotes: 2