I'm wondering if the arrays a and b in the code below are contiguous in memory:
int main() {
int a[3];
int b[3];
return 0;
}
a[0]
,a[1]
and a[2]
should be contiguous and the same for b
, but are there any guarantees on where b
will be allocated in relation to a
?
If not, is there any way to force a
and b
to be contiguous with eachother? i.e so that they are allocated next to eachother in the stack.
The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.
There is no change in implementation weather the stack is in contiguous space or spread though the heap. Some CPU have special instructions to push/pop the stack frame and move the SP all in one instruction so more work is required.
In stack, variables are declared, stored and initialized during runtime. It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variable, and reference variables.
Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack.
No, C++ makes no guarantee about the location of these variables in memory. One or both may not even be in memory (for example if they are optimised out)!
In order to obtain a relative ordering between the two, at least, you would have to encapsulate them into a struct
or class
and, even then, there would be padding/alignment to consider.
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