Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 135 Β· Advanced C

Handling Division by Zero and Arithmetic Traps

Learn what happens when C divides by zero, why integers crash with SIGFPE while floats give inf and NaN, and how to check for INT_MIN / -1 and other traps.

Divide a number by zero on paper and you get "undefined". C takes that word literally: dividing an integer by zero is undefined behavior, and on most computers the program is killed by a signal. Dividing a floating-point number by zero, on the other hand, quietly produces infinity or NaN and keeps going. Both behaviors surprise newcomers, and there's a third, sneakier trap: one specific integer division, INT_MIN / -1, can crash even though the divisor is not zero.

This lesson explains each case, shows what really happens on the sandbox's x86-64 machine, and builds the checks that make arithmetic safe. It builds on Undefined Behavior, Signals and Floating-Point Numbers.

Integer division by zero

The C standard says that if the right operand of / or % is zero, the behavior is undefined. A compiler may then do anything: crash, return garbage, or assume the situation never occurs and optimize the code accordingly. On x86-64 the CPU's idiv instruction raises a hardware exception, and the operating system turns it into the signal SIGFPE ("floating-point exception", although it has nothing to do with floating point here). If the program has no handler, it is terminated.

We can watch this happen safely by installing a handler that reports the signal and exits. A volatile divisor stops the compiler from noticing the zero at compile time:

C The crash behind integer division by zero

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The handler runs, prints its message and calls _exit, so the output ends with the status 1 reported by the runner. Two details matter. First, after SIGFPE caused by a real fault, returning from the handler is itself undefined behavior (the CPU simply re-executes the failing instruction), so handlers must terminate or jump away. Second, only a few functions are safe in a handler; write and _exit are, printf is not. A signal handler is a last-resort diagnostic tool, not a way to continue after the error. The real fix is to never divide by zero.

The remainder operator has the same problem: x % 0 is undefined too.

The other crash: INT_MIN / -1

INT_MIN is the smallest int (usually -2,147,483,648). Its mathematical negation, 2,147,483,648, does not fit in an int, so INT_MIN / -1 overflows, which is undefined behavior for signed integers. On x86-64 the same idiv instruction faults, so this division can also end in SIGFPE, even though neither operand is zero. The same holds for INT_MIN % -1, which the standard also makes undefined.

C A safe division function covering both traps

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function checks the two dangerous inputs before dividing and reports which one it found, so the caller decides what to do: show an error message, use a default value, or give up. Notice that -17 / 5 gives -3 with remainder -2: since C99 division truncates toward zero, and the remainder takes the sign of the dividend. Returning a status and delivering the answer through out-parameters follows the pattern from Error Handling.

Floating-point division by zero

Floating-point arithmetic follows the IEEE 754 standard on nearly every machine, and it defines results for the special cases instead of crashing:

  • x / 0.0 with x > 0 is +inf, and with x < 0 it is -inf.
  • 0.0 / 0.0 is NaN (not a number).
  • Operations on NaN give NaN, and NaN compares unequal to everything, including itself.

Strictly speaking, the C standard leaves this to the implementation, but GCC on Linux, macOS and Windows all use IEEE 754 for double. Because no signal fires, the problem can travel a long way through a program before you see it.

C inf and NaN instead of crashes

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You can test the result with isinf, isnan and isfinite from <math.h>, or ask the floating-point unit what happened with fetestexcept from <fenv.h>: it keeps sticky flags such as FE_DIVBYZERO and FE_INVALID until you clear them with feclearexcept. Never compare against NaN with ==; it is never equal to anything, which is exactly why isnan exists. Many programs avoid special values entirely by checking the divisor first (if (fabs(d) < tiny)), choosing a tolerance that suits the data, since a divisor of 1e-300 is "almost zero" and can overflow to infinity as well.

A checklist for safe arithmetic

  • Check the divisor before every / and % where it could be zero: user input, file data, a count that may be empty (averaging zero items is the classic).
  • For signed integers also check INT_MIN / -1 (and LLONG_MIN / -1 for long long).
  • Prefer returning a status or NULL-like value over aborting, so callers can recover.
  • For floating-point results, test with isfinite before you use or print a number from untrusted input.
  • Don't rely on SIGFPE handlers for recovery. Compile with -fsanitize=undefined while testing: it reports integer divisions by zero and INT_MIN / -1 with the file and line (Sanitizers and Valgrind).
  • Remember unsigned division by zero is just as undefined; only the overflow trap is absent.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does the C standard say about int x = 10 / 0; at run time?

    Integer division by zero is undefined behavior. On x86-64 it usually ends in SIGFPE, but the standard promises nothing.
  2. 2. Which integer division can fail even though the divisor is not zero?

    The true result of INT_MIN / -1 is 2147483648 (for 32-bit int), which does not fit in an int, so the signed overflow is undefined and often faults.
  3. 3. What is 1.0 / 0.0 with IEEE 754 doubles?

    IEEE 754 defines x / 0.0 as infinity for nonzero x. 0.0 / 0.0 is NaN. No signal is raised by default.
  4. 4. How do you reliably test whether a double is NaN?

    NaN is unequal to everything, including itself, so == comparisons are useless. isnan from math.h is the right test.
  5. 5. What is the best way to avoid a division by zero crash?

    Validate input first. A handler cannot safely resume after the fault, and unsigned division by zero is still undefined.

Summary

  • Integer / or % by zero is undefined behavior; on x86-64 it raises SIGFPE and kills the program.
  • INT_MIN / -1 (and INT_MIN % -1) overflows and can fault as well, so safe division must check both cases.
  • Floating-point division by zero follows IEEE 754 on typical systems: x/0.0 is Β±inf and 0.0/0.0 is NaN, with no crash.
  • Test floating results with isnan, isinf and isfinite, or read the FPU flags with fetestexcept.
  • Handlers for SIGFPE can only report and exit, never resume. Validate before dividing, and use UBSan during development.

Next: Debugging C Programs shows how to find faults like these quickly with gdb and sanitizers.