User Tools

Site Tools


Trapping Floating-Point Exceptions in C

This text is regarding programs compiled by GCC. Usually, when a division by zero, or a square root of a negative number occurs, the operation results in a nan (not a number). This value then propagates further in the program. This is reasonable in most cases, since we usually don't want a single division by zero to cause a segfault. However, in the debugging stage, we want the contrary behavior. We want the program to stop so we could backtrace the problem in gdb. To achieve this, we need to unmask a few exceptions. The following should be input to the beginning of your code:

#define _GNU_SOURCE 1
#include <fenv.h>
   static void __attribute__ ((constructor)) trapfpe () {
   /* Enable some exceptions.  At startup all exceptions are masked.  */
programming/trapping_floating-point_exceptions_in_c.txt · Last modified: 2017/05/16 11:10 (external edit)