Activation record

1.4k Views Asked by At

I have hard time understanding activation record ( i have read multiple answers about it ).

Suppose we have a code

  int n( int a){
      int b = a/2;
      return a + b;
  }

 int main (){
     int first   = 1;
     int second  = n(first);
     int third   = 3;
     int fourth  = n(third);
     return 0;
 }

when the program starts to execute , the stack will be filled such as

  | first |
  __________


  | activation_record |
  |   first           |
   ____________________



   | third             | 
   | activation_record |
   | first             |
   _____________________ 



   | activation_record1  |
   |  third              |
   | activation_record   |
   |  first              |
   _______________________

the activation record will put static local variables , function address , function parameters and return value on its stack , should i understand it such as that after activation record ( or the callee function ) is done executing , the activation record is substituted with its return vale and its stack is freed?

Also with same function being invoked multiple times , and having call stack which should hold where to return data, will be the same activation_record pushed into stack or it is created each time function is called? With everything else being said , is it possible to push activation record on stack during compile time?

Thanks for answer

1

There are 1 best solutions below

0
On

You get different answers because different solutions are possible. The C++ Standard only describes observable behavior, and stack layouts aren't observable.

In particular, modern compilers will reduce your program to int main() { return 0; } because only the return value is observable.

If you would have written return fourth;, modern compilers would have figured out that fourth==4 and replaced the program with return 4.

But let's assume for a moment that these optimizations don't happen and you have a regular x64 compiler. Again, the results would be different: The common x64 ABI passes function arguments and return values in CPU registers, not on the stack. This doesn't use all x64 registers, so the local variables can also go in a register.

The different activation records will also overlap, as they're not used concurrently. This is actually not an optimization but necessary, because the compiler in general cannot determine how many calls will be made. Example: for (char&c : string) { c = toupper(c); } .