I am writing some code like this:
while(true) {
int array[5];
// do something
}
For each turn of the loop, the array is a new array. Do I need to delete the array at the end of the loop?
Other answers have correctly explained that a delete
is unnecessary because your array is on the stack, but they haven't explained what the stack is. There's a pretty excellent explanation here: What and where are the stack and heap?
As it applies to your question: in C and C++, unless you explicitly tell the compiler otherwise, your variables are placed in the stack, meaning that they only exist within the scope (that is, the block) in which they're declared. The way to explicitly tell the compiler to put something on the heap is either with malloc
(the C way) or new
(the C++ way). Only then do you need to call free
(in C) or delete
/delete[]
(C++).
Do I need to delete the array in the end of loop?
No, you don't need to delete it because array
has automatic storage duration. It will be released when goes out of each while loop.
You need to call delete [] / new []
, and delete / new
in pairs.
No.
Variables declared on the stack don't need to be manually deallocated. Your array is scoped within the while
loop. For each iteration of the loop, the array is allocated on the stack and then automatically deallocated.
Only an array declared with new[]
must be manually deallocated with delete[]
Also, the array you declare isn't static
in any sense. The static
keyword has a specific meaning in C. The array you declared is actually stored as an auto
(automatic storage) variable, meaning that it is automatically deallocated when it goes out of scope.
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