Why is this C ++ program causing a memory leak?

Consider the following code snippet:

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 can I avoid this?

+5
source share
5 answers

Because you delete str1 twice (the memory that it points to), and you do not delete the allocated memory that str2 first pointed to.

EDIT: I'm not sure what you are trying to achieve.

char* str1 = new char [30];
// str1 = 0x00c06810; (i.e.)
char* str2 = new char [40];
// str2 = 0x00d12340; (i.e.)
strcpy(str1, "Memory leak");

// delete [] str2; should be here

str2 = str1; 
// now str2 == str1, so str2 = 0x00c06810 and str1 = 0x00c06810
// deleting 0x00c06810
delete [] str2; 
// deleting 0x00c06810 once again
delete [] str1;
// 0x00d12340 not deleted - memory leak

If you want this assignment (str2 = str1), first remove str2.

+20
source

The foregoing does not just cause a memory leak; this causes undefined behavior, which is much, much worse.

The problem is the last three lines:

str2 = str1; 
delete [] str2; 
delete [] str1; 

, , . str2, , str1. str2 , , . , , , str2 str1. undefined . , , !

. , . std::string C-, :

string str1 = "Memory leak"; // Actually, it doesn't. :-)
string str2;

str2 = str1; // Okay, make str2 a copy of str1

// All memory reclaimed when this function or block ends

, . .

+21

str1 str2, delete [] str1 delete [] str2 , str1 (str2 ). str2, ( str1 str2)

char* str1 = new char [30];

char* str2 = new char [40]; //or just don't allocate this if You don;t need it

strcpy(str1, "Memory leak");

**delete [] str2;** 

str2 = str1; 


delete [] str1; 
+4

, , , . ,

+2

.

, (, ).

, . , , .

str2 = str1; str2 , str1. .

0

All Articles