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 main() //allocate more memory //Not the same number -- prints a garbage value! num = bar(); //Prints 2 //allocate another number //Prints 2, as we would expect return 0; //return stack-allocated memory //return heap-allocated memory
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.
|