If I declare a data structure globally in a C++ application , does it consume stack memory or heap memory ?
For eg
struct AAA
{
.../.../.
../../..
}arr[59652323];
If I declare a data structure globally in a C++ application , does it consume stack memory or heap memory ?
For eg
struct AAA
{
.../.../.
../../..
}arr[59652323];
Usually it consumes neither. It tries to allocate them in a memory segment which is likely to remain constant-size for the program execution. It might be bss, stack, heap or data.
The problem here is the question. Let's assume you've got a tiny C(++ as well, they handle this the same way) program like this:
main
returns. The string, since it's a constant, is allocated in static data space along with the other strings.static
keyword tells you that it's not to be allocated on the stack.buf1
is on the stack, andmalloc
has a return value of interest; you should always check the return value.For example:
Neither declaring a data structure globally in a C++ consumes heap or stack memory. Actually, global variables are typically allocated in a data segment whose size remains unchanged during the whole program. Stacks and heaps are typically used for variables that get created and destroyed during executing the program.
Global memory is pre-allocated in a fixed memory block, or on the heap, depending on how it is allocated by your application:
EDIT:
The question is confusing: If I allocate a data structure globally in a C++ application , does it consume stack memory or heap memory ?
"allocate"? That could mean many things, including calling malloc(). It would have been different if the question was "if I declare and initialize a data structure globally".
Many years ago, when CPUs were still using 64K segments, some compilers were smart enough to dynamically allocate memory from the heap instead of reserving a block in the .data segment (because of limitations in the memory architecture).
I guess I'm just too old....
Since I wasn't satisfied with the answers, and hope that the sameer karjatkar wants to learn more than just a simple yes/no answer, here you go.
Typically a process has 5 different areas of memory allocated
If you really want to learn what is saved where then read and bookmark these:
COMPILER, ASSEMBLER, LINKER AND LOADER: A BRIEF STORY (look at Table w.5)
Anatomy of a Program in Memory
alt text http://www.tenouk.com/ModuleW_files/ccompilerlinker006.png
Neither. It is .data section.