reset password
Author Message
kknaur
Posts: 540
Posted 21:05 Jan 15, 2014 |

A question was asked in class "Are static arrays created on the stack." And the answer is Yes they are created on the stack and not the heap.  When we start creating dynamic arrays using the new keyword, these arrays will be created on the heap.

yash3ahuja
Posts: 5
Posted 23:18 Jan 15, 2014 |

In case anyone is wondering why I asked this question, it's because it's relatively important for applications. If you are unfamiliar with what the stack and heap do, refer to this excellent stackoverflow answer: http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap.

 

Anyways, if static arrays are allocated on the stack it means that when a function returns, any variables that are allocated on that level of the stack is now essentially garbage memory. If you use one of these stack-allocated variables, you are using memory that isn't actually allocated, which is going to be undefined behavior. Here's an example program showcasing the issue:

#include <iostream>

int* foo();
int* bar();

int main()
{
    int * num = foo();
    
    //Prints 1 on my computer
    std::cout << *num << std::endl;

    //allocate more memory
    int * anotherNum = new int;

    //Not the same number -- prints a garbage value!
    std::cout << *num << std::endl;

    num = bar();

    //Prints 2
    std::cout << *num << std::endl;

    //allocate another number
    int* anotherNum2 = new int;

    //Prints 2, as we would expect
    std::cout << *num << std::endl;

    
    //cleanup
    delete num;
    delete anotherNum;
    delete anotherNum2;

    return 0;
}

//return stack-allocated memory
int* foo()
{
    int array[] = { 1 };
    return array;
}

//return heap-allocated memory
int* bar()
{
    int* num = new int;
    *num = 2;
    return num;
}

 

As you can see, the stack-allocated memory messes up and the heap-allocated memory works as expected. Just making this post so the importance of static arrays being stack-allocated is clear.

Last edited by yash3ahuja at 23:25 Jan 15, 2014.