Fixed a division by zero bug in rtl_fm that appears on OS X

Christoph Gommel cgommel at
Thu Aug 30 22:11:05 UTC 2012

Hallo guys,

I tried to isolate the Floating point exception that prevents rtl_fm
from running on my OS X Machine. XCode's code analysis mechanism
showed pointed out a location of some code that not only might bring
up a division by zero but brought this on my machine.
After adding some basic handling rtl_fm runs now on my Mac but does
not deliver appropiate sound. It's chopped and not understandable.
Despite the fact that gnuradio performs great on the same machine
there seem to be more bugs present I do not understand at the moment.

But first of all this small patch should be added to the main code base.

Sorry for not knowing more about git than executing "git diff" ;( I am
a daily svn user who does not understand the non-linear anarchistic
version management behind git by now...

diff --git a/src/rtl_fm.c b/src/rtl_fm.c
index 0350d8b..d00ef2d 100644
--- a/src/rtl_fm.c
+++ b/src/rtl_fm.c
@@ -313,13 +313,17 @@ int mad(int *samples, int len, int step)
        int i=0, sum=0, ave=0;
        for (i=0; i<len; i+=step) {
                sum += samples[i];
-       }
-       ave = sum / (len * step);
+       }
+       if (len * step) //Avoid Division by zero errors
+               ave = sum / (len * step);
        sum = 0;
        for (i=0; i<len; i+=step) {
                sum += abs(samples[i] - ave);
-       }
-       return sum / (len * step);
+       }
+       if (len * step) //Avoid Division by zero errors
+               return sum / (len * step);
+       else
+               return (0);

 int post_squelch(struct fm_state *fm)

More information about the osmocom-sdr mailing list