I understand that calling new in C++ is equivalent to calling malloc in C, and the pointer returned by the malloc function can be freed when free is called. Array obtained by calling 'new' int[length] are stored in heap. However, what if a static array such as int x[3] = {1,2,3}; was declared? Where will such an array be stored at? Stack?
Asked
Active
Viewed 1,239 times
0
-
1http://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-c – Giorgi Moniava Apr 08 '15 at 07:29
3 Answers
2
a static array (declared at a global scope or in a namespace) will be placed in the data segment. A local array declared inside a function scope will be placed on the stack.
int g_global_array[2] = {4,5,6}; //Data Segment
int main() {
int local_array[3] = {1,2,3}; //Stack
static int s_static = 10; //Also in the Data Segment (static)
return 0;
}
(Same as in plain old C)

odedsh
- 2,594
- 17
- 17
1
Yes, a local array declared this way will be stored in the stack and have a fixed lenght.

Gerard Abello
- 658
- 3
- 7
1
A local array is addressed in the stack. There is a constant size which can't be increased. If you write more values in the array than it can contain, there will be a so called stack overflow. Behind them fields, there is the memory of other values which would be overwritten then. Visual Studio creates some protection bytes to avoid this.

Jonas Aisch
- 71
- 10
-
As far as I know, what you describe isn't a stack overflow, it's an out-of-bounds access of an object that happens to be on the stack. You have a stack overflow when you statically allocate very large data, or when you have too many levels of recursion in one of your functions. In that case, the stack effectively runs out of memory and can't expand enough. – Fabio says Reinstate Monica Apr 08 '15 at 09:01