Tips and Tricks – Best Practices for Programming Defensively in C

Alert light concept and vintage businessman in office

Best practices are meant to be fundamental, essential practices that every firmware application should follow. Programming defensively has always been an important software skill. Below are a few best practices for programming defensively in C that firmware developers should keep in mind:

  • Check inputs and outputs of functions
  • Check the return value of functions (they are ignored so often!)
  • 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, ISR Vector, or stop instruction
  • Watchdog system should be integrated and not blindly pet the watchdog

Following these simple best practices can help ensure improved firmware quality and a first step towards developing secure firmware.

Share >

Leave a Reply

Your email address will not be published. Required fields are marked *

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