Search code examples
c++arraysstaticheap-memorystack-memory

Creating a static array on the heap?


I need to create a very large array. Let us say 50 megabytes.

Can I be safe to create it as a normal static array? Will the compiler put it on the stack (possibly causing a stack overflow), or will it be smart enough to put it on the heap?

If there is no way to do so, is there an easy way to do it with malloc or "new" when program starts, but automatically free it when program ends?


Solution

  • As I understand it, static variables don't live on the stack. If they did, where would they go when you pop the stack frame they live in? Static function variables need to keep their state between calls, so logically, the static data should be kept on the heap.

    Also, when the program ends, everything is automatically deallocated.