Can Valgrind catch all kinds of undefined behavior?

In other words, can I be sure that my undefined program does not work if it runs without Valgrind error messages?

+4
source share
3 answers

There is a fundamental mistake.

Valgrind is not a kind of static analysis tool that understands the semantics of C ++ grammar and therefore knows when you call Undefined Behavior, as stated by C ++ Standard .

Valgrind is a tool that will notify you when you do memory operations that are the result of Undefined Behavior of your program. For example, it will detect when you access unallocated or freed memory, it will detect when you make a system call with an uninitialized (or partially unified) value / buffer, etc.

To accept the medical analogy, Valgrind detects symptoms of Undefined Behavior. The absence of symptoms does not mean the absence of Undefined Behavior.

In addition, since Valgrind only ever checks the code that runs, it will leave the "code" incomplete.

Getting Rid of Undefined Behavior is extremely complex. If your program is non-trivial, it will probably be equivalent to solving the stop problem. However, this should not stop you from taking precautions:

  • Enable compiler warnings: -Wall -Werror set, -Wextra excellent (in addition) for new codebases ( Elementary )
  • Use static analysis tools (some of them, since they do not report the same problems), Clang Static Analyzer, Purify, etc. (good practice)
  • Run Valgrind on an extensive test suite (you can use gcov to test coverage) (Good Practice).
  • Read a few coding standards and consider their advice (do not use them in any other way), Sutter will come first, high quality CPP or MISRA is much more strict and extensive. Some automatic code review tools may check this set of rules. (Nice and reward on a personal level).

Once you have done all this, you probably discovered most of the technical errors in your program. Some, unfortunately, may be hidden. They may be exposed one day after changing optimization parameters, refactoring, or something else ... For more reliable guarantees, you will need a different language.

+4
source

In a word: no. Nothing - not even valgrind - is perfect.

+4
source

After compiling the program, behavior is determined. If you want to detect undefined behavior, you need to start earlier in the toolchain.

Undefined behavior means that the compiler implementation must decide how to implement the behavior, the standard does not dictate what the behavior should be. In other words, it only makes sense to ask about UB for the source code, not for the compiled code.

+4
source

All Articles