Search code examples
memory-managementmemory-leaksfreedynamic-arraysdelete-operator

Problems with deallocating memory in C++ (delete operator)


I'm confused with the delete[] operators in C++. I know it's purpose to deallocate the dynamic memory (heap). But I have tried this code below and found some troubles:

int *dynArrOne = new int[10];
int *dynArrTwo = nullptr;

So it's creating 10 new address in heap from pointer dynArrOne in stack. Then I wrote:

int *dynArrOne = new int[10];
int *dynArrTwo = dynArrOne;

Therefore dynArrTwo and dynArrOne now pointing to same address in heap. The memory in heap will be deallocated if I write: delete [] dynArrOne;. And trouble is that I couldn't deallocated the memory in heap via dynArrTwo: delete [] dynArrTwo. I mean, why did it happen? Why I can't deallocate memory in heap via dynArrTwo?


Solution

  • When you make a copy of a pointer, then that's all you are doing - you are not making a copy of the memory that is pointed-to.

    So, your statement int *dynArrTwo = dynArrOne; is simply duplicating the address stored in the RHS pointer. When the memory pointed to by either variable is released with the delete[] operation, then both pointers will become invalid.

    Think of it this way: I could write down the address of a house (the same address, same house) on two pieces of paper, and give one piece of paper each to two different demolition men. If the first of these demolition guys goes and knocks down the house, then the second one can't, later, go do the same - can he?