Web Toolbar by Wibiya

Pages

Friday, April 13, 2012

Determine direction of stack growth.

Solution #1: The direction of stack growth depends on OS as well as on the architecture. Below is a program to detect the direction of stack growth,

void b(int* x)
{
    int y;

    //if address of y is less than address of x
    //then the direction is downwards, upwards otherwise
    if(&y < x)
        printf("Stack growing downwards.\n");
    else
        printf("Stack growing upwards.\n");
}

void a()
{
    int x;
    b(&x);
}

int main()
{
    a();
    return 0;
}

5 comments:

Anonymous said...

What is the use of determining the direction of stack growth?

Suchit Maindola said...

@Neha: I have no clue :). But I would assume that it doesn't have any use and it is just one of those trick interview questions which check your concepts of memory allocation on stack, pointer arithmetic and use of stack during function calls.

bharat said...

I like the way your code is formatted in this blog. May I know the code formatter you are using in your blogger?

Suchit Maindola said...

Hi Bharat, I use "google-code-prettify".

questborn said...

where did you get this question?