Reputation: 83
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.
Upvotes: 4
Views: 709
Reputation: 234635
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.
Reference: https://en.cppreference.com/w/cpp/language/as_if
Upvotes: 3
Reputation: 1700
Adding on to what @Bhathsheba said whenever you go out of the scope that memory (stack) is not automatically invalidated it's just that you give the freedom of deleting the stack based on other requirements. If there is no other process running then the stack might not get deleted. So it depends on the situation.
Upvotes: 0
Reputation: 48605
You are not wrong. The array gets allocated every time the function is called and de-allocated every time the function ends. Although allocation/de-allocation on the stack is essentially free. Also with an int
array you won't even pay for constructors to run on the elements.
Upvotes: 2