Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor being called on something that was not constructed

Tags:

c++

destructor

The following code gives an exception for g++ version 4.6.2, but runs as expected with g++ version 4.2.1. Messages printed during execution indicate that in both cases a destructor is being called on an address which was never constructed. I would like to know (a) which of the compilers is correct, (b) why is something being destroyed without being created. Thanks much.

//------------------------------------------------------
#include <iostream>
using namespace std;

class Poly{
 private:
  float *coeff;
 public:
  Poly(){
    coeff = NULL;
    cout << "Created "<< this << endl;
  }
  Poly(Poly const & p){          // copy constructor
    coeff = NULL;
    cout << "Executed copy constructor.\n";
  }
  Poly operator=(Poly const & rhs){
    cout << "Executed assignment. " << this << " = " << &rhs << endl;
  }
  Poly fun(){
    Poly c;
    return c;
  }
  ~Poly(){
    cout << "Destructor: " << this << endl;
    delete[] coeff;
  }
};


main(){
  Poly a;
  a = a.fun();
}
//------------------------------------------------------

For g++ 4.6.2 it gives and exception:

% ./a.out
Created 0xbfdcc184
Created 0xbfdcc18c
Executed assignment. 0xbfdcc184 = 0xbfdcc18c
Destructor: 0xbfdcc188
*** glibc detected *** free(): invalid pointer: 0xbfdcc1a8 ***
Aborted

For g++ 4.2.1 it does the following

% ./a.out
Created 0x7fff5fbff930
Created 0x7fff5fbff920
Executed assignment. 0x7fff5fbff930 = 0x7fff5fbff920
Destructor: 0x7fff5fbff910
Destructor: 0x7fff5fbff920
Destructor: 0x7fff5fbff930

There is no exception, and with more code it does produce the correct answer. However, it does seem to be destroying 0x7fff5bff910 which never was constructed. Note that the copy constructor is never called, it would print a message if it had been.

like image 933
Ekalavya Avatar asked Dec 16 '22 03:12

Ekalavya


1 Answers

It looks like your "Poly operator=" does not return anything.

like image 71
innochenti Avatar answered May 03 '23 01:05

innochenti