Optimistic Programming - Embedded.com

Optimistic Programming

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.

Yet when writing the code, we labor under the assumption that there will be no bugs. Bugs are largely treated reactively: Chase 'em down when they appear rather than anticipate how they may arise and appropriately taking defensive action.

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.

Jack G. Ganssle is a lecturer and consultant on embedded development issues. He conducts seminars on embedded systems and helps companies with their embedded challenges. Contact him at . His website is .

2 thoughts on “Optimistic Programming

  1. “Anybody knows any good books or sources for defensive programming in c and c++?nnAny will do anyway. The thing is i had never heard half of the critics, example malloc fails, and I've taken 3/4 of my programming classes in Mexicou00b4s college. Thanks

    Log in to Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.