c++ Destructor de-allocation failing

In the below c++ code, during destructor call, it is crashing with the below error.

If this message is printed, at least the program hasn’t crashed yet! But you may want to print other diagnostic messages too. DSCodes(16782,0x1000efe00) malloc: *** error for object 0x10742e2f0: pointer being freed was not allocated DSCodes(16782,0x1000efe00) malloc: *** set a breakpoint in malloc_error_break to debug

Can someone point me to the mistake in the destructor

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

Answer

In your Pair::Pair(const Pair &obj) you actually copy the pointer, which is double destructed lateron. You want to copy the content of the pointer instead (see the Pair::Pair(int p1, int p2) constructor).

Leave a Reply

Your email address will not be published. Required fields are marked *