global objects in C++
In the following C++ code, where is s allocated? Does it use heap, data, bss, or some combinatio开发者_Python百科n? 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;
}
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:
- on the BSS, with the default constructor run before main()
- on the BSS, with the compiler having determined that all members would be 0 even if the default constructor run, and therefore not running the constructor at all
- in the data segment, with the default constructor run before main()
- in the data segment, with the member variables' initial values calculated by the compiler and written directly into the binary image
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).
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.
精彩评论