priority_queue问题 - 堆后写入内存

时间:2009-11-07 17:55:13

标签: c++ queue heap corruption priority-queue

我正在尝试使用priority_queue,并且程序经常失败并显示错误消息HEAP CORRUPTION DETECTED。

以下是片段:

class CQueue { ...
              priority_queue<Message, deque<Message>, less<deque<Message>::value_type> > m_messages;
...};

类消息重载运算符&gt;和&lt;

我在这里填写队列:

CQueue & operator+=(Message &rhv)
{
    m_messages.push(rhv);  //This is where program fails
    return *this;
}

并在主程序中:

string str;
CQueue pq;
for(int i = 0; i < 12; ++i)
{
    cin >> str;

    Message p(str.c_str(), rand()%12); //Create message with random priority
    pq += p;                           //add it to queue
}

我不知道这似乎是什么问题。当我推送大约8个项目并且它在线失败时会发生这种情况

    push_heap(c.begin(), c.end(), comp);

in&lt;队列&gt;

:(

这是消息类的定义 - 它非常简单:

#pragma once 

#include <iostream>
#include <cstring>
#include <utility>

using namespace std;

 class Poruka
{
private:
char *m_tekst;
int  m_prioritet;
public:
Poruka():m_tekst(NULL), m_prioritet(-1){}

Poruka(const char* tekst, const int prioritet)
{
    if(NULL != tekst)
    {
    //  try{
            m_tekst = new char[strlen(tekst) + 1];
        //}
        //catch(bad_alloc&)
    //  {
    //      throw;
    //  }


        strcpy(m_tekst, tekst);
    }
    else
    { 
    //  try
    //  {
            m_tekst = new char[1];
    //  }
    //  catch(bad_alloc&)
    //  {
    //      throw;
    //  }

        m_tekst[0] = '\0';
    }
    m_prioritet = prioritet;
}

Poruka(const Poruka &p)
{
    if(p.m_tekst != NULL)
    {
        //try
        //{
            m_tekst = new char[strlen(p.m_tekst) + 1];
        //}
        //catch(bad_alloc&)
        //{
        //  throw;
        //}

        strcpy(m_tekst, p.m_tekst);
    }
    else
    {
        m_tekst = NULL;
    }
    m_prioritet = p.m_prioritet;
}

~Poruka()
{
        delete [] m_tekst;
}

Poruka& operator=(const Poruka& rhv)
{
    if(&rhv != this)
    {
        if(m_tekst != NULL)
            delete [] m_tekst;

    //  try
        //{
            m_tekst = new char[strlen(rhv.m_tekst + 1)];
        //}
        //catch(bad_alloc&)
        //{
        //  throw;
        //}

        strcpy(m_tekst, rhv.m_tekst);
        m_prioritet = rhv.m_prioritet;
    }
    return *this;
}

friend ostream& operator<<(ostream& it, const Poruka &p)
{
    it << '[' << p.m_tekst << ']' << p.m_prioritet;
    return it;
}

//Relacioni operatori

friend inline bool operator<(const Poruka& p1, const Poruka& p2)
{
    return p1.m_prioritet < p2.m_prioritet;
}

friend inline bool operator>(const Poruka& p1, const Poruka& p2)
{
    return p2 < p1;
}

friend inline bool operator>=(const Poruka& p1, const Poruka& p2)
{
    return !(p1 < p2);
}

friend inline bool operator<=(const Poruka& p1, const Poruka& p2)
{
    return !(p1 > p2);
}

friend inline bool operator==(const Poruka& p1, const Poruka& p2)
{
    return (!(p1 < p2) && !(p2 < p1));
}

friend inline bool operator!=(const Poruka& p1, const Poruka& p2)
{
    return (p1 < p2) || (p2 < p1);
}

};

Poruka - 消息

2 个答案:

答案 0 :(得分:3)

我认为问题是你的Message对象保持指向原始C字符串的指针,然后这些字符串被取消分配。在这些方面:

cin >> str;

Message p(str.c_str(), rand()%12);

在循环的每次迭代中,您正在读取str的新值,这会使其c_str()方法返回的任何旧指针无效,因此旧消息指向无效数据。您应该更改Message对象,以便将其字符串存储为std::string而不是char*。这会将字符串正确复制到Message对象中。

或者,如果您无法更改Message课程,则必须自行明确复制该字符串,例如使用strdup()malloc() / new[] + strcpy(),然后您必须记住稍后释放字符串副本。

答案 1 :(得分:1)

我不能让它失败。
但是没有足够的信息来编译这一行:

push_heap(c.begin(), c.end(), comp);

但我看到的唯一问题是:

1)您有一个默认构造函数,可以创建一个名为NULL的Poruka:

Poruka::Poruka():m_tekst(NULL), m_prioritet(-1){}

2)没问题,因为你在大多数地方测试它,但是在赋值操作符中你错过了一个测试:

Poruka::Poruka& operator=(const Poruka& rhv)
{
 ....
    // There was no test for 'rhv.m_tekst' being NULL here.
    //
    m_tekst = new char[strlen(rhv.m_tekst + 1)];
    strcpy(m_tekst, rhv.m_tekst);

注意:

  • 使用std :: string类可以使代码更简单。
  • 如果您仍然想使用char *,那么如果您保证它永远不会为NULL,则代码更简单
  • 还有一个更简单的模式来定义标准复制构造函数和赋值运算符。它被称为复制/交换idium。
  • 您不需要定义所有这些关系运算符。有一组模板可以自动运行,参见http://www.sgi.com/tech/stl/operators.html。你只需要定义operator&lt;和operator ==

以下是复制/交换idium的示例

class X
{
     X(X const& copy)
     {
          // Do the work of copying the object
          m_tekst     = new char[strlen(copy.m_tekst) + 1];
          ...
          m_prioritet = copy.m_prioritet;
     }
     X& operator=(X const& copy)
     {
         // I like the explicit copy as it is easier to read
         // than the implicit copy used by some people (not mentioning names litb)
         //
         X  tmp(copy);  // Use the copy constructor to do the work

         swap(tmp);
     }
     void swap(X& rhs) throws ()
     {
         std::swap(this->m_tekst,   rhs.m_tekst);
         std::swap(this->prioritet, rhs.prioritet);
     }