Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global objects in C++

Tags:

c++

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;
}
like image 532
Ravi Avatar asked Mar 26 '26 07:03

Ravi


1 Answers

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).

like image 100
Tony Delroy Avatar answered Mar 27 '26 20:03

Tony Delroy