C/C++ Arena

Step 7 of 7

Challenge: hunt the undefined behavior

Undefined behavior is the biggest source of security holes in C. Learn to spot the usual suspects:

UB Example
Out-of-bounds access a[n] in an array of n elements
Signed overflow INT_MAX + 1
Reading uninitialized memory int x; printf("%d", x);
Null or dangling pointer use *NULL, use after free
Shifting too far 1 << 32 on a 32-bit int
Modifying twice without sequencing i = i++ + 1;

The worst part: UB often seems to work, until a new compiler version, an optimization level or an input changes. On a real machine, -fsanitize=address,undefined catches most of these at runtime (the Pro Track covers it).

Your turn: these two functions each have undefined behavior. Fix both:

Previous: Floating-point rounding