I am trying to learn C++ and was writing programs to learn Copy Constructors and Operator overloading. I am surprised that the below program when Copy constructor is used do
Your program has undefined behavior.
Problems:
data = new char (strlen(str) + 1 );
This doesn't allocate strlen(str) + 1
characters. Instead, it allocates a single character and places the strlen(str) + 1
value within. When you perform a strcpy afterwards, you are corrupting the stack through buffer overflow (writing strlen(str) -1 chars past the allocated space). To allocate an array you should use square brackets:
data = new char [strlen(str) + 1 ];
Second, you should delete the data with delete[] data;
. Otherwise, you get undefined behavior.
Third, your strcpy code doesn't copy the NULL terminator of the string. You should add a null terminator:
data[ strlen(str) ] = 0;
after the strcpy lines; (see comments).
Additionally, there is no requirement that an application would crash on double delete. Deleting the same memory twice is UB.