Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Valgrind catch all sorts of undefined behaviour?

In other words can I be sure that my program is undefined behaviour free if it runs without any Valgrind error messages?

like image 228
ks1322 Avatar asked Dec 17 '22 10:12

ks1322


1 Answers

There is a fundamental error here.

Valgrind is not some sort of static analysis tool that understand the semantics of the C++ grammar and thus know when you are invoking Undefined Behavior as specified by the C++ Standard.

Valgrind is a tool that will however alert you whenever you are doing operations in the memory that are the results of the Undefined Behavior of your program. For example, it will detect whenever you access unallocated or freed memory, it will detect when you make a system call with an uninitialized (or partly unitialized) value/buffer, etc...

To take a medical analogy, Valgrind detects the symptoms of Undefined Behavior. The absence of symptoms does not imply the absence of Undefined Behavior.

Furthermore, because Valgrind only ever inspect code that runs, it will leave some "code" uninspected.

Getting rid of Undefined Behavior is extremely complicated. If your program is non-trivial, it is likely to be equivalent to solving the Halting Problem. However, that should not prevent you from taking precautions:

  • Turn on compiler warnings: -Wall -Werror is a given, -Wextra is great (in addition) for new codebases (Elementary)
  • Use static analysis tools (several of them, since they do not report the same issues), Clang Static Analyzer, Purify, etc.. (Good Practice)
  • Run Valgrind on an extensive test-suite (you can use gcov to check the coverage)(Good Practice)
  • Read several Coding Standards, and think about their advice (do not apply them nilly willy), Sutter's come first, High Quality CPP or MISRA are much more stricter and extensive. Some automatic code review tools can check such a set of rules. (Nice, and rewarding on a personal level)

Once you've done all that, you've probably uncovered most of the technical errors within your program. Some, unfortunately, may be latent still. They may be exposed, one day, following a change of optimization options, a refactoring, or whatever... For stronger guarantees, you'll need another language.

like image 171
Matthieu M. Avatar answered Dec 31 '22 01:12

Matthieu M.