For Code
int main() {
int test;
cin >> test;
while (test--) {
int arr[100];
arr[0] = 0;
}
return 0;
}
Suppose test = 3
.
For the first test case, array is allocated at address 1000
. For the second test case array allocated at 2000
and so on. So, if we have lots of test cases, can our previous allocated memory address be used for further allocation? Does it automatically "free()" our previous allocated memory or it just cannot be used further?
arr
is an automatic variable with block scope. You can use it, take its address etc, only inside the block it is declared. That's what the language specification says. It "comes to life" when we enter the block, and dies when we exit leave block. And that happens every time execution passes through that block; every iteration of the loop.
Compilers take advantage of this requirement by the C++ language. Instead of increasing the memory usage of your program, it's very likely the compiler will re-use the same storage for every iteration of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With