4

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?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Answered here, along with a lot more you should know about C++ storage duration: https://stackoverflow.com/q/6403055/103167 – Ben Voigt Jun 26 '18 at 06:08

3 Answers3

7

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

If you allocate an array with the following code, you will allocate memory in stack. As soon as your code reaches end of the scope ( which is curly bracket ) stack pops out and you are no longer able to access that portion of memory. Yes it is freed automatically.

//anything here

{
 int arr[100];
}

// can not access arr

If you want to access after the curly bracket ( I actually mean changing the scope ), you need to allocate memory in heap for that array. You can do it either by using new keyword or malloc() . But this time you need to free the memory (no auto-free anymore) by using delete and free(), consecutively.

//anything here
int* arr
{
  arr = new int[100];
}

// can access arr
delete [] arr

Please keep in mind that allocating memory in stack is faster but the size of it is limited.

eneski
  • 1,575
  • 17
  • 40
0

The compiler will allocate and deallocate memory in the stack for you if you call int arr[100] (i.e. it will be deallocated after exiting the scope that the variable is in). If you want to manage memory yourself, you need to use int *p = new int[100] and the memory will be allocated in the heap which you can manage yourself. The memory will stay allocated until you call delete[]. If you don't use delete[] after you don't need the memory anymore, you'll get memory leak.

Nyque
  • 351
  • 3
  • 10