gpt4 book ai didi

C++ 重载 >> for ifstream on mac pointer being freed is not allocated

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:37:03 26 4
gpt4 key购买 nike

我正在尝试以下代码,但失败并出现以下错误:

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

最佳答案

我看不出代码有任何明显的错误。正在进行一些不必要的复制(各种运算符应该采用 DataType &(实际上,最好是 const DataType &)而不是像现在这样的对象,以防止对象被复制. 我还会删除 stdio.h 的包含,因为您在此处显示的代码中不需要它。

不过,以上都不会触发您看到的错误。您是否还有任何其他代码没有向我们展示?

关于C++ 重载 >> for ifstream on mac pointer being freed is not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com