Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must I delete a static array in C++?

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?

like image 491
Tian Avatar asked Feb 15 '13 05:02

Tian


3 Answers

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++).

like image 161
Kyle Strand Avatar answered Oct 22 '22 22:10

Kyle Strand


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.

like image 43
billz Avatar answered Oct 22 '22 23:10

billz


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.

like image 1
Charles Salvia Avatar answered Oct 22 '22 23:10

Charles Salvia