For novel ideas about building embedded systems (both hardware and firmware), join the 40,000+ engineers who subscribe to The Embedded Muse, a free biweekly newsletter. The Muse has no hype and no vendor PR. Click here to subscribe.

By Jack Ganssle

Optimistic Programming

Published 4/21/2008

I remain astonished that so many developers continue to write code that assumes relations like1+1=2 are true. In fact, 1+1=0fe23b9, sometimes. Or -65535. Or any of innumerable other values.

1+1=2 only when everything works perfectly. Do your programs work perfectly all of the time? The evidence suggests that most of us create imperfect code. Lots and lots of bugs.

1+1!=2 if any of the parameters are globals and a reentrancy problem stomps on part of a value. Badly encapsulated data has the same problem. A null pointer passed to a summing function can return utterly unpredictable results.

Apparently, gauged by the code I see, none of us has ever dereferenced a null pointer.

I read a lot of code. Most is horribly optimistic. We assume malloc() won't fail (how often do you see malloc()'s error return tested?). Functions never get passed a bad pointer or incorrect data. That divisor in the drug delivery device will never be zero. right? If it is the patient might get the buzz of his life. Stacks are always correctly sized. The A/D won't fail, a cold solder joint won't corrupt input data, and buffers never overflow.

Last year six F-22s bound from Hawaii to Japan lost all their avionics when crossing the International Date Line. They had to follow their tanker back to Hawaii. No doubt the sudden change in longitude wasn't anticipated in the requirements, nor were protective measures against silly results taken in the implementation. The maiden flight of Ariane 5 failed when a 64 bit float, converted to an integer, caused an overflow. Any such conversion would scare most of us, and I hope that fear would translate into an overflow test.

For 50 years programmers have been advised to check the goesintas and goesoutas. But we don't. Here's a short gallery of what results.