What if I delete an array once in C++, but allocate it multiple times?
Does C++ allocate different memory spaces each time I use operator
new
?
Yes.
Does operator
delete
only delete the last allocatedcost
array?
Yes.
You've lost the only pointers to the others, so they are irrevocably leaked. To avoid this problem, don't juggle pointers, but use RAII to manage dynamic resources automatically. std::vector
would be perfect here (if you actually needed an array at all; your example could just keep reading and re-using a single int
).
I strongly advise you not to use "C idioms" in a C++ program. Let the std
library work for you: that's why it's there. If you want "an array (vector) of n integers," then that's what std::vector
is all about, and it "comes with batteries included." You don't have to monkey-around with things such as "setting a maximum size" or "setting it to zero." You simply work with "this thing," whose inner workings you do not [have to ...] care about, knowing that it has already been thoroughly designed and tested.
Furthermore, when you do this, you're working within C++'s existing framework for memory-management. In particular, you're not doing anything "out-of-band" within your own application "that the standard library doesn't know about, and which might (!!) it up."
C++ gives you a very comprehensive library of fast, efficient, robust, well-tested functionality. Leverage it.
There is no cost
array in your code. In your code cost
is a pointer, not an array.
The actual arrays in your code are created by repetitive new int [num]
calls. Each call to new creates a new, independent, nameless array object that lives somewhere in dynamic memory. The new array, once created by new[]
, is accessible through cost
pointer. Since the array is nameless, that cost
pointer is the only link you have that leads to that nameless array created by new[]
. You have no other means to access that nameless array.
And every time you do that cost = new int [num]
in your cycle, you are creating a completely new, different array, breaking the link from cost
to the previous array and making cost
to point to the new one.
Since cost
was your only link to the old array, that old array becomes inaccessible. Access to that old array is lost forever. It is becomes a memory leak.
As you correctly stated it yourself, your delete[]
expression only deallocates the last array - the one cost
ends up pointing to in the end. Of course, this is only true if your code ever executes the cost = new int [num]
line. Note that your cycle might terminate without doing a single allocation, in which case you will apply delete[]
to an uninitialized (garbage) pointer.