Let's say I have the following code:
#include <iostream>
void f() {
int arr[10];
}
int main() {
f();
f();
}
Does the array arr
get deallocated once we leave the scope of f()
, even though we will call it again? Also, if we only call f()
once, I'm assuming it gets deallocated when leaving the scope of f()
, but someone please correct me if I'm wrong.
I also realize that this may be compiler-related question so I've included g++ as a tag. Thanks.
Conceptually it does indeed since arr
has automatic storage duration. (For example, if you were to return a pointer to an element of that array, then the behavior on dereferencing that pointer in the caller would be undefined.)
Whether or not the compiler chooses an appropriate optimisation based on the as-if rule is another matter.
With g++ set to -O3, you can expect your entire program to be compiled to int main(){}
. Check the generated assembly if you're in any doubt.