clang's -fcatch-undefined-behavior not working as advertised

c, c++, clang, undefined-behavior

Solution

Yes: `x` is not an array.

From the documentation:

-fcatch-undefined-behavior: Turn on runtime code generation to check for undefined behavior. This option, which defaults to off, controls whether or not Clang adds runtime checks for undefined runtime behavior. If a check fails, `__builtin_trap()` is used to indicate failure. The checks are:

- Subscripting where the static type of one operand is a variable which is decayed from an array type and the other operand is greater than the size of the array or less than zero.

- Shift operators where the amount shifted is greater or equal to the promoted bit-width of the left-hand-side or less than zero.

- If control flow reaches __builtin_unreachable.

- When llvm implements more __builtin_object_size support, reads and writes for objects that __builtin_object_size indicates we aren't accessing valid memory. Bit-fields and vectors are not yet checked.

I suppose you wanted to test the subscripting check, unfortunately you did not build an array: you built an area of memory (from `malloc`) and then chose to interpret it as an array; but from the point of view of the compiler it is just a chunk of memory (remember than the return type of `malloc` is `void*`).

You could probably test this behavior with:

int main() {
    int x[10] = {};
    printf("%d\n", x[20]);
}

Otherwise, for a specific memory issues tracker, you should look into the Address Sanitizer plugin.

Problem

I built the 3.1 release of llvm/compiler-rt/clang, and I'm trying to see if -fcatch-undefined-behavior really does anything. So far, no luck. E.g. I compile and run ``` #include <stdio.h> #include <stdlib.h> int main() { int* x = malloc(sizeof(int) * 10); printf("%d\n", x[20]); return 0; } ``` with ``` $ /usr/local/bin/clang -fcatch-undefined-behavior undef_test.c && ./a.out 0 ``` Am I missing something really simple?

Original source