【问题标题】:C++ overload >> for ifstream on mac pointer being freed was not allocatedC++ 重载>> for ifstream on mac 指针被释放未分配
【发布时间】:2011-01-20 09:47:03
【问题描述】:

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

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

【问题讨论】:

  • 是这个问题吗?:stackoverflow.com/questions/2234557/…
  • 您是否按照错误消息的提示执行并在malloc_error_break() 上设置了断点?它会很有帮助!
  • 投票关闭,因为不可重现(发布的代码是正确的——错误可能来自不同的代码,或者编译器安装损坏)

标签: c++ ifstream


【解决方案1】:

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

不过,以上都不会触发您看到的错误。还有其他代码你没有给我们看吗?

【讨论】:

    【解决方案2】:

    代码在我看来没问题——我会说问题出在其他地方(可能是安装问题?)您确实有一些不是很好的部分,但没有什么会导致重大问题(例如DataType::getKey 从未使用过,operator&lt;(DataType, DataType) 从未使用过,operator&lt;&lt; 可能应该采用 const 引用而不是值)。

    【讨论】:

    • 我在 Mac 上使用 xcode。我看到 iPhone 开发人员报告了类似的问题。但是,无法从帖子中获得任何有用的信息。不知道是 64 位雪豹导致了这个问题还是我遗漏了一些简单的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2018-09-30
    相关资源
    最近更新 更多