does this reference the pointer returned with "new"?

Advertisements

I have created a char* str_1 and have allocated 64 bits to it.
Then I created another char* str_2 and referenced it to the initial string.

char* str_1 = new char[64];

char* str_2 = str_1; // does it reference the object created with the new statement.

My question is, does str_2 contain the reference to the allocated memory. In which case could I do something like this?

char* str_1 = new char[64];
char* str_2 = str_1;

delete[] str_2;

Is calling delete[] str_2 actually deleting the allocated memory?
Or is it causing a memory leak?

>Solution :

After the declaration of the pointer str_2 the both pointers str_1 and str_2 point to the same dynamically allocated memory (character array).

char* str_1 = new char[64];
char* str_2 = str_1;

After calling the operator delete []

delete[] str_2;

the both pointers become invalid because they do not point to an existent object. And there is no memory leak. You may use either pointer to delete the allocated array. But you may not delete the same dynamically allocated memory twice.

A memory leak occurs when a memory was allocated dynamically and was not freed.

Leave a ReplyCancel reply