Dim St Thomas
Dim St Thomas

Reputation: 123

Strange gcc Initialization crash on old macs

The code below crashes when compiled on an old ppc mac (crash log below code). On a newer mac it prints a blank line and the "Test". I can understand that the order of the test::mName initialization and the initialization of the global test obj may not be guaranteed (in the actual code they are in different files), but it seems that on the old mac, the mName is in some kind of partially initialized state when the constructor is called. Is this code invalid or is there a problem with the compiler?

#include <iostream>
#include <string>

class test
{
public:
  test();
  static std::string mName;
};

test obj;

std::string test::mName("Test");

test::test()
{
  std::cout << mName << std::endl;
}

int main(int argc, char *argv[])
{
  std::cout << obj.mName << std::endl;
  return 0;
}

Crash log:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000fffffff4
Crashed Thread:  0

Thread 0 Crashed:
0   libstdc++.6.dylib                   0x90aa4268 std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char,std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char,std::char_traits<char> >&, std::basic_string<char,std::char_traits<char>, std::allocator<char> > const&) + 64
1   crash                               0x00001b28 test::test() + 48
2   crash                               0x00001de0 __static_initialization_and_destruction_0(int, int) + 144
3   crash                               0x00001e98 _GLOBAL__I_obj + 32
4   dyld                                0x8fe13830 ImageLoaderMachO::doModInitFunctions(ImageLoader::LinkContext const&) + 252
5   dyld                                0x8fe0f244 ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int) + 384
6   dyld                                0x8fe0f368 ImageLoader::runInitializers(ImageLoader::LinkContext const&) + 60
7   dyld                                0x8fe03844 dyld::initializeMainExecutable() + 132
8   dyld                                0x8fe08140 dyld::_main(mach_header const*, unsigned long, int, char const**, char const**, char const**) + 3420
9   dyld                                0x8fe01770 dyldbootstrap::start(mach_header const*, int, char const**, long) + 988
10  dyld                                0x8fe01044 _dyld_start + 56

Upvotes: 0

Views: 83

Answers (1)

Florian Weimer
Florian Weimer

Reputation: 33727

In your example, test is defined before test::mName, so its constructor is executed first, and the access to test::mName in the test::test() constructor is undefined. If it does not result in a crash on other architectures, this is purely by accident.

Upvotes: 1

Related Questions