Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variables contiguous on the stack?

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.

like image 916
Dievser Avatar asked Jan 22 '14 16:01

Dievser


People also ask

Are variables stored on 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.

Is the stack contiguous?

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.

How are variables placed on the stack?

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.

Does stack have contiguous memory?

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.


1 Answers

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.

like image 116
Lightness Races in Orbit Avatar answered Sep 22 '22 19:09

Lightness Races in Orbit