Tips and Tricks – Best Practices for Programming Defensively in C

Defensive programming techniques are easy to forget and overlook when developers are under pressure and simply hacking a functional system together. In order to develop a robust system with a minimal number of defects and access points, developers should remember the following best practices:

  • Check inputs and outputs of functions
  • Monitor buffers to prevent overflow
  • Verify pointers are not NULL, especially function pointers
  • Use assert macro to detect bugs NOT error conditions
  • 2 – 3 % of code base should be assertions
  • assert should NOT modify the state of the system
  • Expose only data and functions that are need to know by larger program (encapsulate)
  • Perform static analysis as part of the build process
  • Monitor the stack for overflows
  • FILL unused ROM with known pattern such as ISR Vector, stop instruction or watermark
  • Develop a robust watchdog system that does not blindly pet the watchdog

Keeping these basic best practices in mind and implementing them will help ensure your embedded software is more robust.