Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function call, rather than variable addresses, used to detect stack growth direction?

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!

like image 807
codeObserver Avatar asked May 21 '11 01:05

codeObserver


People also ask

How do you find direction of a CPU's stack grows up or down )?

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.

Why does the stack address grow towards decreasing memory addresses?

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.

Why are functions stored in 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.


1 Answers

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.

like image 75
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 21:11

Ignacio Vazquez-Abrams