78

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];
Igor
  • 33,276
  • 14
  • 79
  • 112
sameer karjatkar
  • 2,017
  • 4
  • 23
  • 43
  • 2
    also, what is the difference between a global variable and a static variable (within a function). They have to live for the life of the program... – user128026 Jul 23 '09 at 06:19
  • agreed but theirs a difference between accessibility – sameer karjatkar Jul 23 '09 at 06:29
  • @dspinozzi: the constructors for global variables are called before main(), but the constructors for static variables are called the first time the function is called. Both types of variables are typically stored in the same parts of memory -- I think GCC puts them in the .data section. – Neil Jul 24 '09 at 05:26

9 Answers9

143

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

  1. Code - text segment
  2. Initialized data – data segment
  3. Uninitialized data – bss segment
  4. Heap
  5. Stack

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Milan
  • 15,389
  • 20
  • 57
  • 65
  • Does that mean the Uninitialized data - bss and the Initialized - data are a part of the heap ? – sameer karjatkar Jul 23 '09 at 13:36
  • No, they are not a part of the heap, they are in different areas as was written in my answer (the 5 different areas). The heap and stack occupy the virtual memory above the text and data segments. – Milan Jul 23 '09 at 13:53
  • 8
    The important point is that the bss and data segments are allocated when the program is first loaded into memory, and their size does not change while it runs. The contents of the heap by contrast are volatile and change throughout the run, as dynamic memory operations are performed. – quark Jul 24 '09 at 06:50
  • 3
    I thought the idea of letting the stack grow downwards and letting the heap grow upwards was so that they can use the available memory in any ratio. However, isn't that prevented by loading the dynamic libraries in between? – danijar Jan 02 '15 at 11:23
34

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:

/* 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;
}
  1. This is neither allocated on the stack NOR on the heap. Instead, it's allocated as static data, and put into its own memory segment on most modern machines. The actual string is also being allocated as static data and put into a read-only segment in right-thinking machines.
  2. is simply a static allocated pointer; room for one address, in static data.
  3. has the pointer allocated on the stack and will be effectively deallocated when main returns. The string, since it's a constant, is allocated in static data space along with the other strings.
  4. is actually allocated exactly like at 2. The static keyword tells you that it's not to be allocated on the stack.
  5. ...but buf1 is on the stack, and
  6. ... the malloc'ed buffer space is on the heap.
  7. And by the way., kids don't try this at home. malloc 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);
}
Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • 1
    The malloced buffer space has nothing to do with global variables. Only the pointers are global. Please to not confuse the people further. – EFraim Jul 23 '09 at 06:18
  • 10
    Oh, don't be silly. The questioner clearly wasn't clear on what went where, so I wrote an answer that was directed to improving his understanding. – Charlie Martin Jul 24 '09 at 07:19
14

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.

Tomek Kopczuk
  • 2,073
  • 1
  • 14
  • 17
6

Neither. It is .data section.

EFraim
  • 12,811
  • 4
  • 46
  • 62
  • It depends if the global memory was allocated inline or alllocated dynamically from the application – Philippe Leybaert Jul 23 '09 at 06:03
  • 1
    If a memory was allocated dynamically it is not global (in a sense of global variable) – EFraim Jul 23 '09 at 06:06
  • Then in what sense it is global, if it is not in scope of all the program?! – EFraim Jul 23 '09 at 06:11
  • I'd have to agree with EFraim. The actual global variable is going to be located in the .data/.bss sections. Sure in the case of a pointer, it may eventually point to dynamically allocated memory, but I wouldn't say the pointer itself is dynamically allocated. – Falaina Jul 23 '09 at 06:19
  • We're talking about allocated memory which is globally accessible through a global variable. In fact, the compiler can even choose to allocate a pre-allocated block of memory on the heap instead of in a fixed memory block (if the block is too large) – Philippe Leybaert Jul 23 '09 at 06:20
  • If the global variable is going to be located in the data/.bss sections will it show up in the heap memory consumption . I mean will it record its memory consumption under virtual memory ? – sameer karjatkar Jul 23 '09 at 06:25
  • Another point worth noting is that ".data" sections are EXE only (so Microsoft-stuff). There are of course similar structures on other OS's , but the question was not specifically about PC development – Philippe Leybaert Jul 23 '09 at 06:27
  • 2
    @Philippe - the point is that the data pointed to by global pointer **cannot** be considered global. It can even change during program execution (different functions might reset the global pointer to whatever place they want) – EFraim Jul 23 '09 at 06:42
  • 1
    @Philippe: .data sections are also not .EXE only. – EFraim Jul 23 '11 at 19:22
6

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....

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
  • It sais "allocated on the heap" and that's pretty correct. Unless this question is flagged "novice" or "beginner" this should be a sufficient reminder to what is happening. – Don Johe Jul 23 '09 at 06:20
  • @Don: No. The global thing is the pointer, and not the memory it is pointing to. You can handle the memory the way you want. Neither it is there to stay for all the run. You can even point it at stack sometimes. – EFraim Jul 23 '09 at 06:35
  • 1
    If there is one lesson to be learned from this, it's that you should avoid answering questions where the exact meaning of the question is unclear. My answer is not wrong, it's just that some people think that their interpretation of a word is enough to vote down everything that doesn't support their view. Even now, 10 hours after the question was asked, it's still not clear what the OP meant. – Philippe Leybaert Jul 23 '09 at 17:03
5

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.

Program Memory Space

DML
  • 494
  • 5
  • 4
0

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.

Rudi Bierach
  • 341
  • 1
  • 3
-1

global variables live on the heap. these are a special case because they live for the life of the program

user128026
  • 651
  • 4
  • 7
-3

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.

srnayak
  • 103
  • 1