Search code examples
cvariablesmemory

Is contiguous memory allocation for variable guaranteed in c?


#include<stdio.h>
int main()
{
    int a = 1, b = 10, c = 2;
    int *arr[] = {&a, &b, &c}; 
    printf("%d\n", *arr[arr[1]-arr[0]]);
    return 0;
}

Here I am getting output 10. By the output here I understand memory for the variable a b c continuous allocated. Is this output static or it depends on the system? Can I expect the same output in another system? And the contiguous memory allocation for these variable is guaranteed? Here I am using gcc compiler.


Solution

  • arr[1]-arr[0] (which is &b - &a) makes your program have undefined behavior (UB).
    Subtracting 2 pointers not from the same array (or 1 beyond) is UB.

    When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object;
    C2Xdr § 6.5.6 10


    Is continuous memory allocation for variable guaranteed in c?

    No.

    Is this output static or it depends on the system?

    No, it is UB. The system may "work" as hoped sometimes and not others.

    Can I expect the same output in another system?

    Another system may differ. Even the same system may differ on different runs.

    And the continuous memory allocation for this variable is guaranteed?

    No.