As a general rule of thumb, passing the address of stack-allocated ("local") variables as a parameter to a function is OK as long as the function doesn't store the address for later use elsewhere (i.e., after the function returns). That can create a construct known as a "dangling reference", which is what Nothinman was talking about. The memory address would point to an invalid memory location:
int * g_pTheResult; // global pointer to the result of the calculation
int main() {
Calculate();
if ( NULL != g_pTheResult ) {
printf("The result is %d", *pTheResult); // may crash here!
}
return 0;
}
void Calculate() {
int i;
i = 1 + 2 + 3;
g_pTheResult = &i; // error! g_pTheResult is dangling as soon as Calculate() exits
}
The scary part is that the above code might actually RUN and produce the correct output. It's due to the fact that the discarded stack frame from Calculate() is still "sitting around" and simply hasn't been overwritten. So when printf() reads from the address located on this defunct stack frame, the old result (6) will still be there. And while the address is technically invalid, the OS won't be able to detect the invalid memory access because it can only detect invalid Page accesses. Because x86 architectures use 4kb pages and the above functions have stack frames that are only a few bytes long, there is a high probability that both stack frames are on the same (valid) page and the OS would not catch the violation.
Note that the problem with the code above has nothing to do with "reclaiming memory". Reclaiming memory is only an issue when you're dealing with heap-allocated ("dynamic") variables. The compiler ensures all local variables are "reclaimed" appropriately. The programmer gets this for free.