Suppose I have the following snippet.
int main()
{
int num;
int* cost;
while(cin >> num)
{
int sum = 0;
if (num == 0)
break;
// Dynamically allocate the array and set to all zeros
cost = new int [num];
memset(cost, 0, num);
for (int i = 0; i < num; i++)
{
cin >> cost[i];
sum += cost[i];
}
cout << sum/num;
}
` `delete[] cost;
return 0;
}
Although I can move the delete
statement inside the while loop
for my code, for understanding purposes, I want to know what happens with the code as it's written. Does C++ allocate different memory spaces each time I use operator new
?
Does operator delete
only delete the last allocated cost
array?
This procedure deletes: All the logical drives on the array. All data on the logical drives that are part of the array.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.
In C, if you are declaring your array as static ex: int a[10], no need to delete. It will be freed when your function ends or program terminates.
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With