Search code examples
c++pointersmemory-leaksdynamic-memory-allocation

does this reference the pointer returned with "new"?


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?


Solution

  • 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.