[英]C++ segfault under gcc+mingw but not gcc+linux
我在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;
}
我使用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
作为const引用传递(或返回字符串的副本)。
这是因为未定义的行为 。 原因是在getConfiguration
函数中,您按值传递映射,然后返回对此映射中的条目的引用,该函数将在函数返回时被销毁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.