c++ - 为什么此代码会导致 SIGSEGV(gcc 编译器、cygwin 下的 Android NDK 工具链)?

标签 c++ gcc segmentation-fault

TryIt() 函数会导致 SIGSEGV 错误,但仅限于 GCC 而不是 Visual C:

string strs[] = 
{
 "str1",
 "str2",
 "str3",
 ""
};


void Tryit()
{
    int cnt = 0;
    while ( strs[cnt] != "" )
       cnt++;
}

最佳答案

发布的代码是正确的,假设 TryIt() 在构造 strs 之后被调用。由于您提到它是从全局对象的构造函数调用的,因此可能在构造 strs 之前调用它。解决方法是将 strs 包装在一个函数中并调用此函数来获取数组的基址:

std::string* strs() {
    static std::string rc[] p {
         ...
    };
    return rc;
}

关于c++ - 为什么此代码会导致 SIGSEGV(gcc 编译器、cygwin 下的 Android NDK 工具链)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004377/

相关文章:

c - 用 C 链接到一个特定的库

python - 调用成员函数的类实例 : C++ Vs Python syntax

c++ - 用日期创建 std::wstring

c++ - OpenCV 立体校准具有较低的重投影误差,但不正确

c++ - 编织中的降噪算法

c++ - -march=native 到底是做什么的?

c - 为什么 GCC 的 __attribute__((...)) 语法使用双括号?

c++ - 使用筛选算法的段错误(核心已转储)

c - 将 char* 设置为 NULL 段错误

c - 漏洞利用:SIGSEGV、段错误