views:

66

answers:

2

Possible Duplicate:
how does an optimizing c++ compiler reuse stack slot of a function?

do c++ compilers have their ways to determine the time at which, life-time of each local variable in a function ends so that they optimize using stack memory, or they simply take it equal to life-time of the function execution ?

+2  A: 

Most compilers allocate the memory for all variables on the stack in one go. For example:

void f()  {
   int n = 0;      // lifetime of n begins here
   {
      int x = 0;   // lifetime of x begins here
   }               // lifetime of x ends here
}                  // lifetime of n end here 

would allocate memory once, on function entry, for two integers. However, this is an implementation detail, not visible tto the programmer, and the lifetimes of the two variables n and x are not the same.

anon
Assuming of course that the compiler chooses to put the variables on the stack at all, of course.
Ron Warholic
@Ron Hence "Most compilers" in what I wrote.
anon
Just ensuring that it gets mentioned at in at least one of the answers ;)
Ron Warholic
+3  A: 

The memory for stack variables can't be reclaimed before the function has returned. This is because they are part of the stack frame for a particular call. The return pointer is below them, and the caller's frame is above them. Obviously, the return pointer cannot be freed until after the function returns, and so the stack variables are stuck between a rock and a hard place, so to speak, and their memory will remain unusable until after the return.

Borealid