這看起來像我在Apple的libstdc++
中的一個bug,至少在調試模式下編譯時。如果我編譯你上面給兩行減少:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cppfilename;
getline(cin, cppfilename); // error here
return 0;
}
用下面的命令行(從Xcode的默認設置採取在C調試版本++項目定義):
g++ -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1 -g -o getline getline.cpp
然後我讓你看到了同樣的錯誤:
$ ./getline foo
getline(74318) malloc: *** error for object 0x1000021e0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap
這個彈出崩潰報告,這給了我們一個堆棧跟蹤(你也可以通過Xcode的下運行此獲得從調試器堆棧跟蹤;我只是想重現它在清潔的環境中成爲可能,試圖找出原因,沒有別的什麼奇怪的Xcode可能會做):
Thread 0 Crashed: Dispatch queue: com.apple.main-thread
0 libSystem.B.dylib 0x00007fff83c37fe6 __kill + 10
1 libSystem.B.dylib 0x00007fff83cd8e32 abort + 83
2 libSystem.B.dylib 0x00007fff83bf0155 free + 128
3 libstdc++.6.dylib 0x00007fff813e01e8 std::string::reserve(unsigned long) + 90
4 libstdc++.6.dylib 0x00007fff813e0243 std::string::push_back(char) + 63
5 libstdc++.6.dylib 0x00007fff813c92b5 std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, char) + 277
6 getline 0x00000001000011f5 std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) + 64 (basic_string.h:2451)
7 getline 0x0000000100000cbf main + 34 (getline.cpp:10)
8 getline 0x0000000100000c04 start + 52
這看起來極像是對我的錯誤。我們正在使用一些標準的庫函數,儘可能使用最簡單的方法,並觸發斷言失敗。我們不得不放棄file a bug report with our vendor,並嘗試尋找解決方法。如果我們使用的是專有軟件(Apple的許多軟件是幸運的,但幸運的是libstdc++
是自由軟件),我們將不得不放棄file a bug report with our vendor,並嘗試尋找解決方法。幸運的是,這是免費軟件,所以我們可以調查根本原因。不幸的是,我目前沒有時間來追蹤這個問題的根源,但是請仔細閱讀source is available。
您應該可能file a bug about this。在這種情況下,解決方法是刪除_GLIBCXX_DEBUG = 1定義(也可能是_GLIBCXX_DEBUG_PEDANTIC = 1)。你可以在Xcode中找到你的Target,雙擊它生成的可執行文件,進入Build選項卡,確保配置設置爲Debug,滾動到GCC 4的。2 - 預處理部分,並從預處理器宏行中刪除這兩個值。通過這種方式,代碼將生成並運行,並且在這種情況下似乎可以工作,但是您會收到更少的斷言,標準庫的調試版本可能已經能夠捕獲。
我懷疑這裏比你在這裏描述的更多,代碼看起來很好(但格式不正確)。你可能想特別提一下你使用的編譯器版本。我不假設你已經嘗試在malloc_error_break上放置一個斷點? – 2009-12-26 06:03:30
這是整個例子嗎?它運行良好(Windows上的Mingw g ++) – 2009-12-26 06:05:01
是的。它對我來說也很好。我只是困惑,爲什麼我得到的錯誤。 – 2009-12-26 06:06:30