Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor demo (crashing... case 2)

Please have a glance at this program:

class CopyCon
{
public:
char *name;

CopyCon()
{ 
    name = new char[20];        
    name = "Hai";//_tcscpy(name,"Hai");
}

CopyCon(const CopyCon &objCopyCon)
{
    name = new char[_tcslen(objCopyCon.name)+1];
    _tcscpy(name,objCopyCon.name);
}

~CopyCon()
{
    if( name != NULL )
    {
        delete[] name;
        name = NULL;
    }
}
};

int main()
{
    CopyCon obj1;
    CopyCon obj2(obj1);
    cout<<obj1.name<<endl;
    cout<<obj2.name<<endl;
}

This program crashes on execution. Error: "Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)"

If I assign "Hai" to name using aasignment operator, its crashing. Where as when I use string func _tcscpy to assign "Hai" to name, its working perfectly. Can some one explain why so?

like image 451
Akaanthan Ccoder Avatar asked Jan 22 '26 04:01

Akaanthan Ccoder


1 Answers

 name = "Hai";//_tcscpy(name,"Hai");

You are not copying contents of "Hai" into name instead name will point to a read only memory ( whose contents are "Hai") if you try to delete name later then it might crash.

like image 128
aJ. Avatar answered Jan 24 '26 19:01

aJ.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!