Michael
Michael

Reputation: 712

Will delete[] after strcpy cause memory leak?

char* myChar=new char[20];
char* myChar2="123";
strcpy(myChar, myChar2);

...

delete[] myChar;

My question is if strcpy puts a '\0' at the end of "123", then will delete[] myChar only delete the first 3 chars and fail to delete the rest of myChar?

Thank you...

Upvotes: 2

Views: 1655

Answers (5)

AndersK
AndersK

Reputation: 36082

char* myChar=new char[20]; // you allocate 20 space for 20 chars

          +-----------------+
myChar -> | x | x | ... | x | // x = uninitialized char
          +-----------------+

char* myChar2="123";

           +----------------+ 
myChar2 -> | 1 | 2 | 3 | \0 | // myChar2 points to string
           +----------------+ 

strcpy(myChar, myChar2); // copy string to 20 char block
// strcpy copies char by char until it finds a \0 i.e. 4 chars
// in this case

          +----------------------------------+
myChar -> | 1 | 2 | 3 | \0 | x | x | ... | x |
          +----------------------------------+
 // note that characters after the string 123\0 are 
 // still uninitialized

delete[] myChar;

// the whole 20 chars has been freed

Upvotes: 1

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

This is a fundamental aspect of C++ that needs understanding. It causes confusion that has its ground. Look a the example:

char* myChar1 = new char[20];
char* myChar2 = (char*)malloc(20);

In spite of the fact that both pointers have the same type, you should use different methods to release objects that they are pointing at:

delete [] myChar1;
free(myChar2);

Note that if you do:

char *tmp = myChar1;
myChar1 = myChar2;
myChar2 = myChar1;

After that you need:

delete [] myChar2;
free(myChar1);

You need to track the object itself (i.e. how it was allocated), not the place where you keep a pointer to this object. And release the object that you want to release, not the place that stores info about this object.

Upvotes: 1

Vishal
Vishal

Reputation: 3296

Delete doesn't look for "\n" while deleting a character string.

Rather the compiler looks for "\n" while allocating the memory-chunk for your string.

Hence, deleting both myChar, and myChar2 would hence work in exactly the same way, by looking at the size of memory-chunk that was actually allocated for the particular pointer. This emplies no memory leaks in your situation.

Upvotes: 1

Alexander Mihailov
Alexander Mihailov

Reputation: 1152

Your delete[] deallocates all of 20 chars, not only 3+1 that you really did use.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206546

No, delete [] deallocates all the memory allocated by new [] as long as you pass the same address to delete [] that was returned by new [].
It just correctly remembers how much memory was allocated irrespective of what is placed at that memory.

Upvotes: 3

Related Questions