Eds
Eds

Reputation: 380

Is it correct to delete indirect pointer

I am still new to C++, so please be kind when answering. When it comes to dynamic memory management, many tutorials give an example or similar of below, which often times they are in the same scope.

MyClass * pt;
pt = new MyClass[3];
delete[] pt;

Which I have a question what if I lost access to the original dynamic allocated variable but only have the address of it. Consider the following

int* intP; //Global variable

void SomeFunction()
{
    int* intP2 = new int;
    *intP2 = 10;
    intP = intP2;

    //Some other actions.....and lost access to intP2 when this function ends
}


void SomeOtherFunction()
{
    delete intP; //Valid?
}

Upvotes: 2

Views: 177

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

This behavior is well-defined: all pointers pointing to the same location in memory are fair game for deletion. In fact, the same mechanism is at work when you construct objects inside a function, which is a reasonably common scenario:

MyClass *create(size_t size) {
    MyClass *res = new MyClass[size];
    ... // Do something else
    return res;
}
...
MyClass *array = create(100);
...
delete[] array;

Here is what is happening above:

  • The result of new is assigned to res
  • The pointer is returned to the caller, while the original variable res goes out of scope
  • You delete array to free memory that was allocated with new [] and assigned to res inside create() function.

In situations when another pointer remains accessible, it becomes illegal to dereference the other pointer after deletion, for example:

int *data = new int[200];
int *copy = data;
...
delete[] copy;
// At this point it becomes illegal to dereference data[]

Upvotes: 3

Related Questions