【问题标题】:pointer being freed was not allocated error?被释放的指针没有分配错误?
【发布时间】:2013-11-02 01:00:16
【问题描述】:

我看过很多关于这个错误的帖子。但我没有动态保留内存或在析构函数中做任何事情: 本程序为操作系统中选择柱面的SSJF算法。

我有一个简单的类叫做 IO:

class IO
{
    public:
            IO();
            IO(int,int);
            void setIO(int,int);
            ~IO();
            int trackNo;
            int arrival;
            int start;
            int end;
            bool finished;
};

这里是类的实现::

IO::IO(int arr, int tNum)
{
    this->arrival = arr;
    this->trackNo = tNum;
    this->start = 0;
    this->end = 0;
}    
IO::IO()
{

}

IO::~IO()
{

}    
void IO::setIO(int t1, int t2)
{
    this->trackNo = t1;
    this->arrival = t2;
}

最后是主程序的一部分:

list<IO> myList;
....
myList.push_back(tmpIO); //Add to the list
...
list<IO> wt_list;

后来我尝试做一些操作。我删除了一些不相关的部分。

    //list<IO>::iterator itMin;
    while(myList.size()>0)
    {
        //If it is the first input just get it
        if(f)
        {

            IO selected = myList.front();
            curr_time += selected.arrival + selected.trackNo;
            f=false;
            cout << selected.arrival<<endl;
            lastPos = selected.trackNo;
            myList.pop_front();

        }
        //Check if there is any item to add to queue
        while(myList.front().arrival <  curr_time)
        {
            wt_list.push_back(myList.front());
             myList.pop_front(); //Error is coming from this line
        }

        while(wt_list.size()>0)
        {

        }

错误信息:

malloc: * 对象 0x10f68b3e0 的错误:未分配被释放的指针 * 在 malloc_error_break 中设置断点进行调试

任何人都可以帮助我并解释为什么我会收到此错误以及如何跳过它?

【问题讨论】:

  • 那么,你从哪里得到错误?你试过在调试器中运行你的程序吗?
  • 请发布确切的错误消息,并(如果可能)将 cmets 添加到您的代码示例中以显示错误所指的行。
  • 我添加了更多信息。错误来自我评论过的第三方。
  • 抛出错误时myList中有多少项?
  • 换句话说,在抛出错误之前,你调用mylist.pop_front()mylist.size()是什么此时

标签: c++ list


【解决方案1】:

我能想出的重现此错误的最简单代码如下所示:

#include <list>

int main()
{
    std::list<int> mylist;
    mylist.pop_front();
}

我可以通过这样做来防止错误:

#include <list>

int main()
{
    std::list<int> mylist;
    if (!mylist.empty())
    {
        mylist.pop_front();
    }
}

你来电:

myList.pop_front();

...在while-loop 中,而while-loop 也调用myList.pop_front()

我只能建议你调试你的代码,看看pop_front()mylist 调用了多少次。我的钱超过了mylist.size() 次,hence my question in the comments(新的重点):

myList 中有多少项抛出错误时

也许最简单的解决方法是替换...

    //Check if there is any item to add to queue
    while(myList.front().arrival <  curr_time)
    {
        wt_list.push_back(myList.front());
         myList.pop_front(); //Error is coming from this line
    }

    while(wt_list.size()>0)
    {

    }

...与...

    while (!mylist.empty() && myList.front().arrival < curr_time)
    {
        wt_list.push_back(myList.front());
        myList.pop_front();
    }

    while (!wt_list.empty())
    {
    }

...但是从您提供的 sn-p 很难分辨。

【讨论】:

  • 非常感谢您的回答。你是对的。几次迭代后列表为空...
  • 我认为可能是这样。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 2011-08-06
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
相关资源
最近更新 更多