basics · beginner · ~10 min
Recognize implicit conversion in signed/unsigned compares.
Implement int safer_lt(int a, size_t b) returning 1 if a < b is true in the mathematical sense (treating a as signed and b as unsigned but with negative a always meaning 'less than any nonneg b'), else 0.
In plain if (a < b) C promotes a to size_t, turning -1 into SIZE_MAX. The safer version checks the sign first.
if (signed_var < unsigned_var) triggers implicit conversion that flips negative numbers to huge positives. Real-world CVEs (e.g. in mmap-size validation) come from this.
signed int, unsigned size_t.
0 or 1.
No casts that hide the rule.
#include <stddef.h>
int safer_lt(int a, size_t b) { /* TODO */ return 0; }
Writing the naïve return a < b; and not catching that -1 < (size_t)5 evaluates false because (size_t)-1 == SIZE_MAX.
a == INT_MIN; a == 0, b == 0; large b near SIZE_MAX.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.