簡體   English   中英

C ++段錯誤在gcc + mingw下但不是gcc + linux

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM