2

次のコードを試していますが、次のエラーで失敗します:

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

ファイル input.txt の内容は次のとおりです。完全な権限があり、ファイルはデバッガーで正常に開かれます。助けてください。

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;
    }    
}
4

2 に答える 2

1

コードに明らかに問題があることはわかりません。不必要なコピーが行われています (さまざまな演算子は、オブジェクトがコピーされないようにするために、現在のようにオブジェクトではなくDataType &(実際には、できればconst DataType &) を使用する必要があります。stdio.h のインクルードも必要ないので削除します)。ここに表示しているコードについて。

ただし、上記のいずれも、表示されているエラーをトリガーするものではありません。あなたが私たちに見せていない他のコードはありますか?

于 2010-02-24T07:01:02.623 に答える
0

コードは私には問題ないように見えます-問題は他の場所にあると思います(おそらくインストールの問題ですか?)正確に優れていない部分がいくつかありますが、大きな問題を引き起こすものは何もありません(たとえば、DataType::getKey使用されていません、operator<(DataType, DataType)使用されることはありませんoperator<<。おそらく、値の代わりに const 参照を使用する必要があります)。

于 2010-02-24T06:18:36.953 に答える