C++段错误在gcc + mingw下但不是gcc + linux

Eli*_*oux 2 c++ gcc mingw

我在Mingw的一个大型程序中有一个sefault,但不是在Linux下.我设法将其减少为以下代码:

#include <iostream>
#include <string>
#include <map>

using namespace std;

const std::string& getConfiguration(const std::string& key, std::map<std::string, std::string> configuration)
{
    map<string, string>::const_iterator it = configuration.find(key);
    return it->second;
}

int main() {
    map<string, string> testmap;
    testmap["key"] = "value";
    map<string, string>::const_iterator it;
    it = testmap.find("key");
    const string& value = it->second;
    cout << value << endl;
    cout << "ok!" << endl;
    const string& valuebis = getConfiguration("key", testmap);
    cout << valuebis << endl;
    cout << "Mingw segfaults before here" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我使用mxe编译它,具有以下选项

/path/to/mxe/usr/bin/i686-w64-mingw32.static-g++ -ggdb3 -O0 -o test.exe test.cpp -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32
Run Code Online (Sandbox Code Playgroud)

(但我得到的结果与i686-pc-mingw32.static相同)我在gdb中收到以下错误:

Starting program: Z:\test-conv.exe
[New Thread 17328.0x43b4] 
value
ok!

Program received signal SIGSEGV, Segmentation fault.
std::operator<< <char, std::char_traits<char>, std::allocator<char> > (__os=warning: RTTI symbol not found for class 'std::ostream'
..., __str=<error reading variable: Cannot access memory at address 0xfeeefee2>)
    at /home/eroux/softs/mxe-64/tmp-gcc-i686-w64-mingw32.static/gcc-4.9.1.build/i686-w64-mingw32.static/libstdc++-v3/include/bits/basic_string.h:2777
2777    /home/eroux/softs/mxe-64/tmp-gcc-i686-w64-mingw32.static/gcc-4.9.1.build/i686-w64-mingw32.static/libstdc++-v3/include/bits/basic_string.h: No such file or directory.
(gdb) bt
#0  std::operator<< <char, std::char_traits<char>, std::allocator<char> > (__os=warning: RTTI symbol not found for class 'std::ostream'
..., __str=<error reading variable: Cannot access memory at address 0xfeeefee2>)
    at /home/eroux/softs/mxe-64/tmp-gcc-i686-w64-mingw32.static/gcc-4.9.1.build/i686-w64-mingw32.static/libstdc++-v3/include/bits/basic_string.h:2777
#1  0x0040181a in main () at ConventionTest.cpp:22
Run Code Online (Sandbox Code Playgroud)

我的猜测是,getConfiguation中的迭代器以某种方式被mingw释放,而不是通常的linux gcc ...

但是因为它在Linux下工作正常并且因为gcc根本没有发出任何警告(即使有-Wextra),我想知道某个地方是否存在不良实践(我不是C++专家)或者它是否是mingw优化中的错误...

谢谢,

Jar*_*d42 5

getConfiguration返回对本地对象的引用(并调用UB),configuration作为const引用传递(或返回字符串的副本).


Som*_*ude 5

这是因为未定义的行为.原因是在getConfiguration函数中按值传递映射,然后返回对此映射中的条目的引用,该函数将在函数返回时被销毁.