Must I delete a static array in C++?

12,647

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
12,647
Tian
Author by

Tian

Updated on July 24, 2022

Comments

  • Tian
    Tian almost 2 years

    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?

  • Kyle Strand
    Kyle Strand about 11 years
    Yes, it probably is, since "delete" shouldn't have any meaning when applied to variables on the stack. Can you suggest a better wording?
  • Kyle Strand
    Kyle Strand about 11 years
    (The reason I worded it that way original was because the original question was "do I need to delete the array," i.e., is it necessary to do so, and the answer is no, it's not necessary.)
  • Kyle Strand
    Kyle Strand about 11 years
    Yes, I did mean heap. Thanks. Though that would have been more helpful as a comment than as an edit to an old comment, since I didn't actually get a notification for the edit.
  • Kyle Strand
    Kyle Strand about 11 years
    Why would you consistently use something from the standard library without even knowing what the application is?
  • billz
    billz over 8 years
    @dtc nope, you can't delete objects which are not newed.