Program crashes on delete

  • Thread starter Thread starter Mockingbird0
  • Start date Start date
M

Mockingbird0

Guest
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class iint
{
public:
iint();
~iint();
iint(int);
iint(iint&);
iint& operator=(iint&);
iint& operator+(int);
void display();
protected:
int val;
};

iint::iint() : val(0) {}
iint::iint(int i) : val(i) {}
iint::~iint()
{
cout << "Destroying iint " << hex << this << endl;
}
iint::iint(iint& i0)
{
val = i0.val;
}
iint& iint::operator=(iint& i0)
{
val = i0.val;

return *this;
}
iint& iint::operator+(int i0)
{
iint *i1 = new iint(val);
i1->val += i0;

return *i1;
}
void iint::display()
{
cout << dec << val << "_" << endl;
}

int main()
{
string s;

iint ii0(7);
ii0.display();

iint ii1 = ii0 + 7;
ii1.display();

delete &ii1; //program crashes here when trying to exit destructor

cout << "Press <ENTER> to exit." << endl;
getline(cin,s);
}

I am running this program in a VS2017 environment.

This program crashes when it executes the delete &ii1 instruction. Why?

Of course I could simply define a local object in the + operator and return the result by value. But I want to know why the program does not run as written.

Sometimes (not every time) I get the following message: "HEAP: Invalid address specified to RtlValidateHeap()".

Continue reading...
 
Back
Top