Description
Using external input as an integer divisor without checking for zero can cause undefined behavior and terminate the program.
Potential impact
- Process termination or repeated request failures can cause denial of service.
Remediation
Before division, verify that the divisor is nonzero and within its permitted range. Check numeric input syntax and conversion errors too.
Examples
Before
c
int divisor = atoi(argv[1]);
int result = 100 / divisor;
After
c
int divisor = atoi(argv[1]);
if (divisor == 0) { return; }
int result = 100 / divisor;
The first excerpt divides by user input without a zero check. The second rejects zero before dividing.
These excerpts compare only the zero check. In actual input handling, ensure the argument exists and use a conversion such as strtol that lets you check errors and range, instead of atoi.