I just watched an interesting talk on UB and I tried out some things.
Consider the following code:
#include <limits.h>
#include <stdio.h>
int f(int x) {
return x + 10;
}
int main(void) {
int i;
i = INT_MAX - 3;
printf("i = %d\n",i);
printf("f(%d) = %d\n",i,f(i));
printf("Hello World\n");
return 0;
}
When compiling using:
clang -O0 -fsanitize=undefined a.c
And then running the programm, there will occur a runtime error and clang will explain in detail what’s wrong:
runtime error: signed integer overflow: 2147483644 + 10 cannot be represented in type 'int'
However, the programm will continue past the offending line and execute the Hello World message, and the exit status / return code will be 0, as if nothing bad has happened.
My question is:
How do I force a hard crash / exception (like an assert() error) in my C programm when that happens using clang?
Thanks for any helpful answers in advance.
PS: I learned that the error message cannot be produced in compile time, only during runtime, but I didn’t expect that the consequences were so loose when enabling -fsanitize=undefined.
Expectations:
clang -O0 -fsanitize=undefined a.c -o a.out
./a.out
echo $?
Hello Worlddoes not appear- exit status is != 0
>Solution :
https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
For most checks (checks), the instrumented program prints a verbose
error report and continues execution upon a failed check. You can use
the following options to change the error reporting behavior:
-fno-sanitize-recover=...: print a verbose error report and exit the program;
-fsanitize-trap=...: execute a trap instruction (doesn’t require UBSan run-time support). If the signal is not caught, the program will
typically terminate due to a SIGILL or SIGTRAP signal.
It sounds like you want to use -fsanitize=undefined -fno-sanitize-recover=all.