我在 big program 中有一个错误在 Mingw 下,但在 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;
}
我用 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
(但我得到与 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
我的猜测是 getConfiguation 中的迭代器以某种方式被 mingw 释放,而不是被通常的 linux gcc 释放...
但由于它在 Linux 下工作正常并且 gcc 根本没有发出警告(即使使用 -Wextra
),我想知道是否有什么不好的做法(我不是 C++ 专家)或如果它是 mingw 优化中的错误...
谢谢,
最佳答案
getConfiguration
返回对本地对象的引用(并因此调用 UB),将 configuration
作为常量引用传递(或返回字符串的拷贝)。
关于gcc+mingw 下的 C++ 段错误,但不是 gcc+linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25594316/