Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can locally allocated memory be used for future uses?

Tags:

c++

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?

like image 618
Saurav Chandra Avatar asked Jan 02 '23 05:01

Saurav Chandra


1 Answers

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.

like image 122
StoryTeller - Unslander Monica Avatar answered Jan 05 '23 18:01

StoryTeller - Unslander Monica