nlsandler / writing-a-c-compiler-tests

Test cases for Writing a C Compiler
https://nostarch.com/writing-c-compiler
Other
149 stars 17 forks source link

chapter_7/valid/extra_credit/goto_sibling_scope.c is undefined behavior #31

Closed meithecatte closed 2 months ago

meithecatte commented 3 months ago

The test, as currently written, requires that variables stay alive even outside of the block they are declared in:

int main(void) {
    int sum = 0;
    if (1) {
        int a = 5;
        goto other_if;
        sum = 0;  // not executed
    first_if:
        sum = sum + a;  // sum = 11
    }
    if (0) {
    other_if:;
        int a = 6;
        sum = sum + a;  // sum = 6
        goto first_if;
        sum = 0;
    }
    return sum;
}

See:

C17 6.2.4.2. The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime.

C17 6.2.4.6. For [an object with an automatic storage duration] that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.

Thus, after goto first_if;, the lifetime of int a begins anew, and its value is not initialized when it is read (which is UB due to 6.3.2.1.2).

nlsandler commented 3 months ago

Ah, good catch - I believe you're right, this is undefined.

It looks like this UB isn't detected by -Wuninitialized in either GCC or Clang, by -fanalyzer in GCC, or by Clang's Memory Sanitizer. I think it would be worth filing issues against GCC and Clang for those false negatives; would you like to file those or should I?

meithecatte commented 3 months ago

I'm not interested in handling the upstream reports, but feel free to drop the links here once you get to it.