2011-12-29 26 views
1

在我的Mac下面的程序段錯誤(獅子):C++:GCC 4.2.1給出了程序,它出現segfaults,而不是在運行GCC 4.2.1 Linux的

#include <iostream> 

using namespace std; 
struct A{ 
    friend std::ostream& operator << (std::ostream& os, const A& a) { 
    os << 3 << endl; 
    } 
}; 

template <typename T> 
T f() { return T();} 

int f() { return 2;} 


int main() { 
    cout << f() << endl; 

    A a= f<A>(); 
    cout << a << endl; 
} 

當我運行程序時,我得到:

./a.out 
2 
3 
Segmentation fault: 11 

當我做一個堆棧跟蹤,我得到:

(gdb) run 

Starting program: a.out 
unable to read unknown load command 0x24 
unable to read unknown load command 0x26 
2 
3 

Program received signal SIGSEGV, Segmentation fault. 
0x00007fff8b84fa49 in ??() 
(gdb) bt 
#0 0x00007fff8b84fa49 in ??() 
#1 0x00007fff665c1ae8 in ??() 
#2 0x0000000000000000 in ??() 

回溯沒有有用的信息(任何人都知道爲什麼嗎?)。這在linux中正常工作 。

+3

你的'operator <<'被聲明爲返回'std :: ostream&',但是你沒有'return'語句。 – ildjarn 2011-12-29 20:44:02

+0

我沒有你的環境去測試,但我最好的猜測是你的main結尾沒有'return 0;'。 ETA我認爲@ ildjarn的評論是比我更好的猜測。 – 01d55 2011-12-29 20:45:46

+0

你用'-g'編譯過嗎? – 2011-12-29 20:48:46

回答

6

讓我們更清楚發生了什麼

(cout << a) << endl; 

你在你的operator<<忘了return

+1

特別是你應該返回引用到ostream – 2011-12-29 20:47:36

+0

我明白我的錯誤。編譯器應該阻止我編譯,而不是在運行時導致seg錯誤的程序。 – user231536 2011-12-29 21:53:40

+0

@ user231536:編譯器發出警告的可能性很大。 – ildjarn 2011-12-29 21:57:05

相關問題