Home > Enterprise >  does this reference the pointer returned with "new"?
does this reference the pointer returned with "new"?

Time:07-28

I have created a char* str_1 and have allocated 64 bytes 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?

CodePudding user response:

After the declaration of the pointer str_2, both pointers str_1 and str_2 are pointing 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;

Both pointers become invalid, because they both do not point to an existing object.

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 at all.

CodePudding user response:

str_1 and str_2 are pointing to the same piece of allocated memory, so you could use either str_1 or str_2 to free that memory.

However, don't use both to free the memory, that would be a double delete. And don't use either pointer after you have freed the memory.

  • Related