Consider the following piece of code:
char* str1 = new char [30];
char* str2 = new char [40];
strcpy(str1, "Memory leak");
str2 = str1;
delete [] str2;
delete [] str1;
Why does the above program cause a memory leak? How do I avoid this?
Because you’re deleting str1 (the memory it points to) twice and you don’t delete the memory allocated under where str2 was first pointing to.
EDIT:
I’m not sure what you’re trying to achieve.
If you want that assignment (str2 = str1) then delete str2 first.