首页 > 解决方案 > 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

标签: macosgcccompiler-errorsinitializationpowerpc

解决方案


在您的示例中,test是在之前定义的,因此首先执行其构造函数,并且构造函数中test::mName的访问是未定义的。如果它不会导致其他架构崩溃,这纯粹是偶然的。test::mNametest::test()


推荐阅读