c++variablescontiguous

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.


Solution

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