Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are global structs allocated on the stack or on the heap?

Tags:

c++

struct

I am writing in an environment where I am not allowed to allocate new memory after program startup, nor am I allowed to make operating system calls. In tracking down a page fault error (likely caused by inadvertently violating one of the above) the question occurs to me (since this bit me in the butt with std strings)

Is a global/local struct allocated on the stack or heap? For example:

If this statement is in the global scope

struct symbol {
    char blockID;
    int blockNum;
    int ivalue;  
    double fvalue;
    int reference;
    bool isFloat, isInt, isRef;
    int symbolLength;
} mySymbol;

where is the memory for it allocated?

like image 601
Stephen Avatar asked Sep 20 '11 15:09

Stephen


People also ask

Are structs stored on the heap or stack?

If the object is of struct type then it may be stored on stack (as a local variable) or on the heap (as a field of another object).

Are globals in the heap?

Global variables have static storage duration. They are stored in an area that is separate from both "heap" and "stack". Global constant objects are usually stored in "code" segment, while non-constant global objects are stored in the "data" segment.

Can structs only be allocated to the heap?

Are struct instances sometimes allocated on the heap? Yes, they are sometimes allocated on the heap.

Where in memory is the struct stored?

Always, contiguous(adjacent) memory locations are used to store structure members in memory. Consider below example to understand how memory is allocated for structures.


1 Answers

It's implementation-defined (the C++ standard doesn't really talk about stack and heap).

Typically, objects with static storage duration (such as globals) will end up in a special segment of address space that is neither stack nor heap. But the specifics vary from platform to platform.

like image 123
Oliver Charlesworth Avatar answered Nov 14 '22 23:11

Oliver Charlesworth