2010-02-24 31 views
2

我想下面的代碼,它失敗,出現以下錯誤:文件input.txt中的C++ Mac上的指針超載>>對於ifstream的被釋放沒有被分配

malloc: *** error for object 0x10000d8c0: pointer being freed was not allocated 
*** set a breakpoint in malloc_error_break to debug 
Program received signal: 「SIGABRT」. 

以下是內容:它有完整的權限和文件在調試器中成功打開。請幫忙。

Jacob Anderson 
Michael Thomson 
Joshua Smith 
Mathew Matheis 
Ethan Evans 
Emily Drake 
Emma Patterson 
Madison McPhee 
Hannah Briens 
Ashley Schmidt 

#include <iostream> 
#include <vector> 
#include <functional> 
#include <algorithm> 
#include <list> 
#include <fstream> 
#include <string> 

#include <stdio.h> 

using namespace std; 

struct DataType { 
    string lastname;    // (Key) Student's Last Name 
    string firstname;  // Student's First Name 

    string getKey() const 
    { return lastname; } // Returns the key field 
}; 

ostream& operator << (ostream& os, DataType myData) { 
    os<<myData.firstname<< " "<<myData.lastname; 
    return os; 
} 

bool operator < (DataType lhs, DataType rhs) { 
    if (lhs.firstname < rhs.firstname) 
     return true; 
    return false; 
} 

int main() { 
ifstream studentFile ("input.txt"); // Student file 
    list <DataType> students;   // Students 
    DataType currStudent;    // One Student (has firstname,lastname) 

    if (! studentFile.is_open()) 
    { 
     return -1; 
    } 
    while (studentFile >> currStudent.firstname >> currStudent.lastname) { 
     students.push_back(currStudent); 
    } 

    list<DataType>::iterator i = students.begin(); 
    while (i != students.end()) { 
     cout << *i << endl ; 
     ++i; 
    }  
} 
+2

這是什麼問題? :http://stackoverflow.com/questions/2234557/c-using-getline-prints-pointer-being-freed-was-not-allocated-in-xcode – ergosys

回答

0

代碼看起來沒事,我 - 我想說的問題是從其他地方你確實有一些作品是不完全很大,但沒有什麼是應該引起(可能是安裝問題?)主要問題(例如,從不使用DataType::getKey,從不使用operator<(DataType, DataType),應該使用operator<<而不是值)。

+0

我在Mac上使用xcode,我看到類似的問題,由iPhone開發者,但是,無法從帖子中獲得任何有用的信息。不知道它是否是64bit的snow leopa rd導致問題或簡單的我缺少的東西 – Kiran

1

我看不出任何明顯的代碼錯誤。有一些不必要的複製正在進行(各個操作員應該採取DataType &(實際上,最好是const DataType &)而不是像他們現在所做的那樣防止複製對象。我也會刪除包含stdio.h,因爲您不需要需要,對於代碼你在這裏展示。

的無上述應觸發您看到的錯誤,雖然,有沒有你不向我們展示任何其他代碼?

相關問題