In other words can I be sure that my program is undefined behaviour free if it runs without any Valgrind error messages?
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:
-Wall -Werror
is a given, -Wextra
is great (in addition) for new codebases (Elementary)gcov
to check the coverage)(Good Practice)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With