Search code examples
c++optimizationstackblock

In C++ block scope, is re-using stack memory the area of optimization?


I tested the following codes:

void f1() {
  int x = 1;
  cout << "f1  : " << &x << endl;
}

void f2() {
  int x = 2;
  cout << "f2  : " << &x << endl;
}

void f3() {
  {
    int x = 3;
    cout << "f3_1: " << &x << endl;
  }
  {
    int x = 4;
    cout << "f3_2: " << &x << endl;
  }
}

int main() {
  f1();
  f2();
  f3();
}

in release build, the output is...

f1  : 00FAF780
f2  : 00FAF780 
f3_1: 00FAF780
f3_2: 00FAF780  <-- I expected

but in debug build,

f1  : 012FF908
f2  : 012FF908
f3_1: 012FF908
f3_2: 012FF8FC  <-- what??

I thought the rule was to move the stack pointer to use the stack memory again when the block is ended.
Is this principle the area of optimization?


Solution

  • A debug build is usually very unoptimized on purpose. It might be that each variable, regardless of scope, is given its own spot on the stack so that when your code crashes it can show you the state of each one. This wouldn't be possible if they all shared an address.