How to achieve memory safety while writing C code?

Viewed 225

I was recently asked in the following question in an interview: "What are all the possible ways to achieve memory safety while writing C code?"

I replied about secure versions of APIs. The interviewer said that there are more approaches than that. I want to ask what is the list of ways to achieve memory safety.

1 Answers
  • NULL out pointers always when freeing memory to avoid Use-After-Free bugs and double free bugs
  • Always perform bound check to avoid OOB (Out-Of-Bounds) read and OOB write vulnerabilities
  • Try not to use recursion, or just use it when knowing your limits, so preventing Stack Exhaustion and Heap Exhaustion vulnerabilities
  • If you suspect a pointer could be NULL at any time, check it always before using it to avoid NULL pointer dereference vulnerabilities
  • Use multi-thread hardening mechanisms to avoid race conditions leading to memory-safety bugs
  • Initialize always pointers and variables, specially if they are going to be used / accessed without prior value assignment
  • Always ensure a string is properly NULL-terminated, to avoid memory leaks and other memory safety issues
  • Be sure copying functions, specially when using loops, are properly designed not to surpass one byte into a subsequent buffer or variable (off-by-one vulnerability)
  • Carefully select types and casts to avoid problems like integer overflows

and a lot more...

Related