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];
Global memory is pre-allocated in a fixed memory block, or on the heap, depending on how it is allocated by your application:
byte x[10]; // pre-allocated by the compiler in some fixed memory block
byte *y
main()
{
y = malloc(10); // allocated on the heap
}
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....
If you are explicitly allocating the memory yourself by new or malloc, then it will be allocated in heap. If the compiler is allocating the memory, then it will be allocated on stack.
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 global object itself will take up memory that the runtime or compiler reserves for it before main is executed, this is not a variable runtime cost so neither stack nor heap.
If the ctor of the object allocates memory it will be in the heap, and any subsequent allocations by the object will be heap allocations.
It depends on the exact nature of the global object, if it's a pointer or the whole object itself that is global.
The probelm here is the question. Let's assume you've got a tiny C(++ as well, they handle this the same way) program like this:
/* my.c */
char * str = "Your dog has fleas."; /* 1 */
char * buf0 ; /* 2 */
int main(){
char * str2 = "Don't make fun of my dog." ; /* 3 */
static char * str3 = str; /* 4 */
char * buf1 ; /* 5 */
buf0 = malloc(BUFSIZ); /* 6 */
buf1 = malloc(BUFSIZ); /* 7 */
return 0;
}
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:
char * bfr;
if((bfr = malloc(SIZE)) == NULL){
/* malloc failed OMG */
exit(-1);
}