Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Stack Doesn't Roll Back

We've studied that Stack expands and shrink. But in practice it doesn't happen Take an example of a stack which expands from addresses 100 to 0 i.e. first variable goes to 100, then next to 99 etc. Now when we write the following code

int main()
{
   {
      int i;
      cout<<&i;//100 is displayed on screen
   }
   {
      int j;
      cout<<&j;//99 is displayed on screen
   }
}

Now when we declared i, it goes to address 100 and then its scope finishes. Then j is declared in a new scope and now it should have address 100 again because i is finished and stack should roll back but it doesn't, j has address 99. WHY? can you explain??

like image 876
Ahmed Avatar asked May 31 '26 09:05

Ahmed


1 Answers

The standard makes no such promise about the the storage of local variables. There is no reason to believe that the order of declaration has any relationship with the order in which they are laid out in memory.

It is entirely at the behest of the compiler how it is done. Indeed, for your program, the compiler could use the same address for both variables. I would expect any decent optimising compiler to do so.

Now, in practice, compilers may well use the sorts of optimisations that you talk about. But how these optimisations are implemented will vary from compiler to compiler. And there's no reason for the simple rule that you describe to apply universally to all functions. The compiler may choose one strategy for one function, and a different strategy for a different function. The compiler may behave differently depending on its options.

Of course, if you are talking about the stack frames associated with function calls, then it is different. Clearly when you make a new function call, a new stack frame is allocated. And then when the function returns, that stack frame is destroyed, and the calling function's stack frame is re-entered. But that's an entirely different matter, and is not what you discuss in the question.

like image 76
David Heffernan Avatar answered Jun 02 '26 23:06

David Heffernan