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?
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).
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.
Are struct instances sometimes allocated on the heap? Yes, they are sometimes allocated on the heap.
Always, contiguous(adjacent) memory locations are used to store structure members in memory. Consider below example to understand how memory is allocated for structures.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With