Search code examples
cglobal-variablesstandards-compliance

C externs that alias the same address?


Can a C compiler assume that two different extern globals cannot be aliased to the same address?

In my case, I have a situation like this:

extern int array_of_int[], array_end;

void some_func(void)
{
    int *t;
    for (t = &array_of_int[0]; t != &array_end; t++)
    {
    ...

The resulting binary compiled with optimization on does not test the

t != &array_end
condition before entering the loop. The compiler's optimization is that the loop must execute at least once since t cannot immediately equal &array_end at the outset.

Of course we found this the hard way. Apparently, some assembler hackery with linker sections resulted in a case where the two externs are the same address.

Thanks for any advice!


Solution

  • In short, yes, it's free to make that assumption. There is nothing special about extern variables. Two variables may not be aliases of each other. (If the answer was any different, think about the chaos that would ensue. extern int a, b could alias each other, which would make the semantics of any code using those variables completely insane!)

    In fact, you are relying on undefined behaviour here, full stop. It is not valid to compare addresses of unrelated variables in this way.