Here is the program…
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char;
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete name;
name = NULL;
}
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.name = "Hello";
cout<<objCopyCon2.name<<endl;
return 0;
}
Once the code execution completes, when the destructor called, it crashes on ‘delete’ saying…
Debug Error!
Program: …
HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
Don’t we have to clear the heap memory in destructor. What’s wrong with this program? Pls someone help!
Copy constructor works perfectly as intended. But still… !?
The problem is you are allocating only one
charin the copy constructor.In
mainyou are assigning a 4-byte string (remember the null), but when you copy the object, you only allocate enough room for 1 byte.What you probably want to do is change
to
And in the destructor:
to
Also:
You are assigning
"Hai"and"Hello"toobjCopyCon1.namewhich is hiding the memory allocated in the constructor. This memory can never be freed!