linux 下内存检查工具 valgrind 及 sanitizer 编译选项及静态检查工具
要记住,这两个工具都是动态检查工具,也就是程序运行时覆盖到的代码才会被检查,未覆盖的代码是不会检查的。
valgrind是一个模拟程序运行环境并记录程序非法内存使用的一个程序工具。可能慢一些,因为是外部模拟。Valgrind慢,像调试器一样,它无法扩展。如果您要处理大型数据集,则可能会花费很长时间,人们经常不理会“执行时间”,如果您处理小问题则可以不关心,但是性能是生活质量的基本要素,我认为您不应或不能在模拟的生产环境中运行valgrind。
sanitizer是google开发的一个编译工具集(编译选项),最初为llvm开发,后来gcc(g++) 4.9版及更新版也集成了这个编译工具。可能快一些,因为直接编译进去了。sanitizer更精细精确,因为有很多选项可以开关,但正因为是编译选项,因此很多时候环境无法让你使用sanitizer,最主要是编译器不允许。
两个都好用。
1 sanitizer
如果系统里面无法直接安装valgrind,则可以考虑使用 sanitizer 来进行调试。为了更好的调试,系统里可能需要安装 libasan 库(特别是使用 Address Sanitizer的时候)。
when you build with the flag -fsanitize=address, if you are using C++ then it is worth setting -fno-omit-frame-pointer too as you will get better results.
Address Sanitizer
The Address Sanitizer (asan for short) is very similar to Valgrind’s default “memcheck” tool. use -fsanitize=address to enable it.
Thread Sanitizer
The Thread Sanitizer (tsan for short) is designed to find race conditions in your code, very similar to the “Helgrind” tool in Valgrind. It has a typical slowdown of 5x – 15x and a memory overhead of 5x – 10x. Very much like the Address Sanitizer you compile it in using a simple flag, -fsanitize=thread. You should not try to use this with the asan flag. This won’t compile.
Undefined Behaviour Sanitizer
The Undefined Behaviour Sanitizer (ubsan for short) does exactly what it says on the tin, it detects undefined behaviour usage in your application that can lead to bugs and portability issues and it is extremely fast. There are a whole bunch of different options to turn on here but the ones I typically use are -fsanitize=undefined -fsanitize=nullability.
不知道valgrind有没有 Undefined Behaviour Sanitizer 这个功能。经过查证,valgrind好像还没有类似工具。
参考网址:
https://github.com/google/sanitizers
https://clang.llvm.org/docs/AddressSanitizer.html
2 valgrind
如果系统可以安装 valgrind,则推荐使用valgrind,毕竟这个不影响代码,而且可以调试 java 及 golang等很多程序,直接调试程序。
不过,这两个工具要在打印中显示 问题行号,则需要使用 -g -O0 来编译。也可以加上 -g3。
Helgrind 相当于 Thread Sanitizer。
不知道valgrind有没有 Undefined Behaviour Sanitizer 这个功能。经过查证,valgrind好像还没有类似工具。
静态检查工具:
static analyzers like clang-tidy, cppcheck, PVS