提问者:小点点

C++析构函数解分配失败


在下面的C++代码中,在析构函数调用期间,它会崩溃,并出现以下错误。

如果打印了这条消息,至少程序还没有崩溃!但您可能还想打印其他诊断消息。DSCodes(16782,0x1000EFE00)malloc:***对象0x10742E2F0错误:未分配释放的指针DSCodes(16782,0x1000EFE00)malloc:***在malloc_error_break中设置断点以调试

有人能告诉我解构器的错误吗

class Pair {
 public:
  int *pa,*pb;
   Pair(int, int);
   Pair(const Pair &);
  ~Pair();
 };
 
Pair::Pair(int p1, int p2)
{
    this->pa = new int;
    this->pb = new int;
    *pa = p1;
    *pb = p2;
}
Pair::Pair(const Pair &obj)
{
    this->pa= new int;
    this->pb = new int;
    this->pa = obj.pa;
    this->pb = obj.pb;
}
 
Pair::~Pair()
{
    if(pa)
        delete (pa);
    if(pb)
        delete(pb);
}
 /* Here is a main() function you can use
  * to check your implementation of the
  * class Pair member functions.
  */
  
int main() {
  Pair p(15,16);
  Pair q(p);
  Pair *hp = new Pair(23,42);
  delete hp;
  
  std::cout << "If this message is printed,"
    << " at least the program hasn't crashed yet!\n"
    << "But you may want to print other diagnostic messages too." << std::endl;
  return 0;
}

共2个答案

匿名用户

在Pair::Pair(const Pair&obj)中,实际上复制了指针,它是双倍析构的。您希望复制指针的内容(请参阅pair::pair(int p1,int p2)构造函数)。

匿名用户

问题是,您的复制构造函数将另一个对象的p1p2分配给了当前对象(q持有与p相同的p1p2)。因此在程序结束时,q的析构函数和p的析构函数尝试删除两个相同的指针。

在复制构造函数中,应该复制整数,而不是只复制指针。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|析|构|函数|解|分配|失败)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?