Course contentsShow
← C
Lesson 941 of 1,21913. Advanced CFree lesson

Tools to detect UB: UBSan

Tools to detect UB: UBSan

What you'll learn: How to use the Undefined Behavior Sanitizer (UBSan) to automatically catch invisible bugs in your code at runtime.

The Invisible Enemy

Undefined Behavior (UB) is the "Dark Side" of C because it is often silent. If you access an array out of bounds or cause an integer overflow, your program might not crash immediately. Instead, it might keep running with corrupted data, acting like a ticking time bomb that only explodes when a customer uses it.

Think of UB like a slow gas leak in a house. You can’t see it or smell it, and the lights still turn on, but eventually, the smallest spark will cause a disaster. UBSan is your electronic leak detector.

Meet UBSan

UBSan (Undefined Behavior Sanitizer) is a tool built into modern compilers like GCC and Clang. It works by "instrumenting" your code. When you turn it on, the compiler injects tiny "checkers" into your program. If your code does something illegal while it's running, UBSan will immediately print a clear error message explaining exactly what went wrong and which line of code caused it.

How to use it

To use UBSan, you simply add a specific flag during compilation: -fsanitize=undefined.

Consider this problematic code that tries to shift a bit too far:

#include <stdio.h>

int main() {
    int x = 1;
    // Shifting a 32-bit int by 32 bits is Undefined Behavior!
    int result = x << 32; 
    
    printf("Result: %d\n", result);
    return 0;
}

If you compile this normally, it might print 0, 1, or something else entirely depending on your CPU. But if you compile with UBSan:

gcc -fsanitize=undefined main.c -o program

When you run ./program, the tool will intercept the error and print: runtime error: shift exponent 32 is too large for 32-bit type 'int'

Why use it?

You should use UBSan during development and testing, but not usually in the final product you ship to users (as the extra checks make the program slightly slower). It turns "weird glitches" into "obvious errors," saving you hours of painful debugging. It is your first line of defense against the unpredictable nature of the C language.

Key takeaway

UBSan is a compiler flag (-fsanitize=undefined) that makes your program "scream" the moment it hits Undefined Behavior, turning invisible bugs into readable error reports.