I read different responses to the question of detecting stack growth detection and I understand that, in modern architectures, stack might grow randomly, might be created off heap, and so on.
However, in this classic interview question, I want to understand why people use a function call rather than comparing 2 local variables in the same function. I think there must be some particular reason for doing this but, not being a C/low level developer [Java :)], I am simply guessing.
Here is the code I tried:
void sub (int *a) {
int b;
int c;
printf ("a:%d\n", a);
printf ("b:%d\n", &b);
printf ("c:%d\n", &c);
if (&b > a) {
printf ("Stack grows up.\n");
} else {
printf ("Stack grows down.\n");
}
}
int main (void) {
int a;
int b;
sub (&a);
printf ("\nHere we go again!!\n");
if (&b > &a) {
printf ("Stack grows up.\n");
} else {
printf ("Stack grows down.\n");
}
return 0;
}
I also found this article which tries to optimize the solution which I don't understand either: http://www.devx.com/tips/Tip/37412
P.S: From different responses to this and other threads, it seems like the question itself is flawed/irrelevant, as an interview question it probably re-enforces incorrect assumptions unless someone researches the answer !
Thanks!
Call the function 'fun()' from the main function. And Compare addresses of two local variables. If the address of fun()'s local variable is more than the main's local variable, then the stack grows upward otherwise it grows downward.
On x86, the primary reason the stack grows toward decreasing memory addresses is that the PUSH instruction decrements the stack pointer: Decrements the stack pointer and then stores the source operand on the top of the stack.
We use Stack for storing temporary data such as local variables of some function, environment variables which helps us to transition between the functions, etc. We interact with the stack using PUSH and POP instructions.
You can't fully control the order the compiler chooses to allocate the local variables in. You can however reasonably control the functions that will be called, and in what order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With