Technical Interview question: Stack growth direction

This one is a brain teaser for my native programmers.

Prove via code the direction of a threads’ stack growth i.e is it upwards or downwards.

Post your answer as a comment. I’ll post mine in a while.

8 thoughts on “Technical Interview question: Stack growth direction

  1. void* func1()
    {
    int x =0;
    return &x;
    }

    int _tmain(int argc, _TCHAR* argv[])
    {

    // method 1
    void* nextStack = func1();
    void* nCurrentStack = &nextStack;
    if( nextStack > nCurrentStack )
    std::cout<<"Stack moving downwards"<<std::endl;
    else
    std::cout<<"Stack moving upwards"<<std::endl;
    return 0;
    }

    • @Naveen
      I think there is a bug. Aren’t you returning an address of a local variable from func1()? Stack space will be reclaimed once func1 returns. Eventually when you are calling func1 twice you end up having same address returned the second time unless the stack would have changed by another operation which resulted in a push.

      • As long as i am not trying to access the memory returned by the function, there is no problem. Also no matter how many times you call this function, you will always get the same result.

        But i must say, John’s code is much cleaner..

  2. #include

    void stackTest(const int * mainInt) {
    int localInt = 0;
    ptrdiff_t diff = &localInt – mainInt;
    std::cout << "Stack growing " < 0) ? “up” : “down”) << std::endl;
    }

    void _tmain(int, _TCHAR**) {
    int main_x = 5;
    stackTest(&main_x);
    }

  3. This is how I would do it 🙂

    void PrintStackGrowthDir()
    {
    	char a = ''; // a will be allocated higher on the stack 
    	char b = ''; // b will be allocated lower on the stack (at a lower address than 'a')
    	printf("Stack growing %s", &b < &a ? "downward" : "upward");
    }

Appreciate your comments...