Global memory management in C++ in stack or heap?

64,026

Solution 1

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

Solution 2

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);
}

Solution 3

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.

Solution 4

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

Solution 5

Neither. It is .data section.

Share:
64,026
Alex Carman
Author by

Alex Carman

Updated on July 05, 2022

Comments

  • Alex Carman
    Alex Carman almost 2 years

    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];
    
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    It depends if the global memory was allocated inline or alllocated dynamically from the application
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    global memory is never allocated on the stack. The stack is only used for local variables and parameters
  • EFraim
    EFraim almost 15 years
    If a memory was allocated dynamically it is not global (in a sense of global variable)
  • Alex Carman
    Alex Carman almost 15 years
    By editing the boot.ini file we can extend the virtual memory to 3GB . Like wise is there any setting for the memory segment ?
  • EFraim
    EFraim almost 15 years
    Then in what sense it is global, if it is not in scope of all the program?!
  • user128026
    user128026 almost 15 years
    stack variables are "destroyed" when the function returns
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    That would be pointless, because the size of the statically allocated memory can never change
  • EFraim
    EFraim almost 15 years
    The malloced buffer space has nothing to do with global variables. Only the pointers are global. Please to not confuse the people further.
  • Falaina
    Falaina almost 15 years
    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.
  • Don Johe
    Don Johe almost 15 years
    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.
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    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)
  • Alex Carman
    Alex Carman almost 15 years
    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 ?
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    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
  • EFraim
    EFraim almost 15 years
    @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
    EFraim almost 15 years
    @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)
  • Alex Carman
    Alex Carman almost 15 years
    Does that mean the Uninitialized data - bss and the Initialized - data are a part of the heap ?
  • Milan
    Milan almost 15 years
    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.
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    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.
  • Alex Carman
    Alex Carman almost 15 years
    Yes that's my mistake in framing the question . I have edited it now
  • quark
    quark almost 15 years
    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.
  • Charlie Martin
    Charlie Martin almost 15 years
    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.
  • EFraim
    EFraim almost 13 years
    @Philippe: .data sections are also not .EXE only.
  • danijar
    danijar over 9 years
    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?
  • philx_x
    philx_x almost 6 years
    does initializing a pointer to NULL go in the data or bss segment? route_t* tblhead = NULL;