macos - 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
解决方案
在您的示例中,test
是在之前定义的,因此首先执行其构造函数,并且构造函数中test::mName
的访问是未定义的。如果它不会导致其他架构崩溃,这纯粹是偶然的。test::mName
test::test()
推荐阅读
- python - python中ARIMA的参考
- android - 保存列表
到sqlite - apiconnect - API Connect - 已发布的产品在 Developer Portal 中不可见,但没有错误?
- c# - 函数谓词到字符串
- python - 如何在 Python 中实现良好的移动平均线
- dictionary - 字符串内的presto lambda函数变量
- c# - 如何在 Xunit 中为集合编写 Assert 语句?
- csv - 将大 csv 文件部分导入 Neo4j
- sql - 在实体框架中使用事务的问题
- javascript - 通过单击图像在一个容器中显示/隐藏不同的信息:隐藏前显示信息