Sep 132013

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 Responses to “Technical Interview question: Stack growth direction”

  1. This is how I would do it 🙂

    void PrintStackGrowthDir()
    	char a = '\0'; // a will be allocated higher on the stack 
    	char b = '\0'; // b will be allocated lower on the stack (at a lower address than 'a')
    	printf("Stack growing %s", &b < &a ? "downward" : "upward");
  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;

  3. 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;
    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..

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.