Defensive Programming - Friend or Foe? | Interrupt

One of the worst things about embedded development (especially in C) is receiving a return value of -1 or unknown_error from a function, with no other information about why the failure took place. It provides no information about where the error bubbled up from!


This is a companion discussion topic for the original entry at https://interrupt.memfault.com/blog/defensive-and-offensive-programming
void my_free(void *p) {
const size_t num_bytes = prv_get_size(p);
free(p);
// Set each word to 0xbdbdbdbd
memset(p, 0xbd, num_bytes);
}

Ouch, this is evil. The memset() should be in any case before the free()

Good point! I’ll fix that up.

Be aware that the memset call is likely to be removed if optimizations are enabled. With GCC, you can use the -fno-builtin-memset flag to prevent this, but that may pessimize the generated code elsewhere.

Thanks for the inspiring article! I would like to ask what is meant by “state machine generators” in this article. Which ones do you prefer to use? Are you planning an article on this topic?

You can find them all over Github usually. The ones I immediately know of are:

There are more, and there are probably better ones than the ones listed above.

1 Like

I’m really glad to see that other fellow embedded software developers reach similar conclusions about facing software errors head on (otherwise known as Design by Contract – DbC).

In a shameless self-promotion, I’d like to mention my articles and blogs about the same subject matter:

1 Like

I really like your fuse analogy.
It really hit the nail on the head for me. :wink: