Math Result Not Representable
Production Risk
Integer overflow from unvalidated string parsing is a frequent source of security vulnerabilities.
ERANGE (errno 34) is set when a math function produces a result that overflows or underflows the representable range of the return type. It is also set by strtol() and strtod() when parsed values are out of range.
- 1exp() or pow() producing a value larger than DBL_MAX (overflow → HUGE_VAL)
- 2A very small result underflowing to 0
- 3strtol() parsing a string like "99999999999999999999" that exceeds LONG_MAX
Parsing an out-of-range integer with strtol.
#include <stdlib.h>
#include <errno.h>
errno = 0;
long val = strtol("99999999999999999999", NULL, 10);
// val = LONG_MAX, errno = ERANGEexpected output
strtol returns LONG_MAX, errno = ERANGE
Fix
Check errno after strtol/strtod and validate ranges
WHEN When parsing numeric strings from external input
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char *end;
errno = 0;
long val = strtol(input, &end, 10);
if (errno == ERANGE || val > INT_MAX || val < INT_MIN) {
// handle out-of-range
}Why this works
errno is set to ERANGE on overflow. Always check errno after strtol/strtod, and also verify that end != input (non-empty parse) and *end == '\0' (full parse).
✕ Use atoi() for input parsing
atoi() has undefined behaviour on overflow — it does not set errno. Use strtol() with errno checking instead.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev