Should I delete a static array in C ++?

I am writing code like this:

while(true) { int array[5]; // do something } 

For each rotation of the loop, an array is a new array. Do I need to delete the array at the end of the loop?

+7
source share
4 answers

Do I need to delete an array at the end of the loop?

No , you do not need to delete it, because array has an automatic storage duration. It will be released when exiting the while loop.

You need to call delete [] / new [] and delete / new in pairs.

+12
source

Not.

Variables declared on the stack do not need to be manually freed. Your array is within the while . For each iteration of the loop, the array is allocated on the stack and then automatically freed.

Only an array declared with new[] should be manually freed with delete[]

Also, the declared array is not static in any sense. The static has a specific meaning in C. The declared array is actually stored as the variable auto (automatic storage), which means that it is automatically freed when it goes out of scope.

+1
source

You cannot (unless you use complex assembly) and you must not delete arrays or objects allocated on the stack.

If for some reason you feel the need to delete the created array, follow these steps:

 int *array = new int[5]; //do something delete[] array; 

Also, my advice is to use std::vector instead of arrays.

0
source

Other answers correctly explained that delete not required because your array is on the stack, but they did not explain what the stack is. There is a rather excellent explanation here: What and where is the stack and heap?

How does this apply to your question: in C and C ++, unless you explicitly tell the compiler otherwise, your variables are pushed onto the stack, which means that they exist only within the scope (that is, the block) in which they are "declared A way to explicitly tell the compiler to put something in the heap either using malloc (path C) or new (path C ++). Only then you need to call free (in C) or delete / delete[] (C ++) .

0
source

All Articles