開源C++/C代碼檢查工具
Cppcheck
cppcheck是靜態的C/C++ 代碼分析工具,用以檢查內存泄漏,錯配的內存分配和釋放,緩沖區溢出等問題。支持eclipse插件。
Someof the checks that are supported include:
- Automatic variable checking
- Bounds checking for array overruns
- Classes checking. (e.g. unused functions, variable intialisation and memory duplication).
- Usage of Deprecated or superseded functions according to http://www.opengroup.org
- Exception safety checking, for example usage of memory allocation and destructor checks
- Memory leaks, e.g. due to lost scope without deallocation
- Resource leaks, e.g. due to forgetting to close an filepointer.
- Invalid usage of Standard Template Library functions and idioms
- Miscellaneous stylistic and performance errors
http://en.wikipedia.org/wiki/Cppcheck
Splint是靜態檢查C語言安全弱點和編寫錯誤的程序。檢查主要包括:未使用的變量,類型不一致,使用未定義的變量,內存管理錯誤(內存泄露,懸浮指針等),緩沖區溢出,無法執行到的程序,忽略返回值,無限循環等。
Problemsdetected by Splint include:
- Dereferencing a possibly null pointer (Section 2);
- Using possibly undefined storage or returning storage that is not properly defined (Section 3);
- Type mismatches, with greater precision and flexibility than provided by C compilers (Section 4.1–4.2);
- Violations of information hiding (Section 4.3);
- Memory management errors including uses of dangling references and memory leaks (Section 5);
- Dangerous aliasing (Section 6);
- Modifications and global variable uses that are inconsistent with specified interfaces (Section 7);
- Problematic control flow such as likely infinite loops (Section 8.3.1), fall through cases or incomplete switches (Section 8.3.2), and suspicious statements (Section 8.4);
- Buffer overflow vulnerabilities (Section 9);
- Dangerous macro implementations or invocations (Section 11); and
- Violations of customized naming conventions. (Section 12)
.源文檔 <http://splint.org/manual/html/sec1.html>
經過初步測試splint相對于cppcheck更為強大,而且當前版本更為穩定。
Valgrind:
Valgrind是一個用于檢查程序內存泄漏、段錯誤等bug的工具。它包含的有:內存檢測、緩存檢測、代碼覆蓋、性能測試等功能。Valgrind的最初作者是Julian Seward,他于2006年由于在開發Valgrind上的工作獲得了第二屆Google-O'Reilly開源代碼獎。
Valgrind是運行在 Linux上一套基于仿真技術的程序調試和分析工具,它包含一個內核——一個軟件合成的CPU,和一系列的小工具,每個工具都可以完成一項任務──調試,分析,或測試等。Valgrind可以檢測內存泄漏和內存違例,還可以分析cache的使用等,靈活輕巧而又強大,能直穿程序錯誤的心臟,真可謂是程序員的瑞士軍刀。它包括Memcheck,Callgrind, Cachegrind, helgrind等一些列的工具。
Memcheck是其中最常用的工具,用來檢測程序中出現的內存問題,所有對內存的讀寫都會被檢測到,一切對malloc()/free()/new/delete的調用都會被捕獲。所以,它能檢測以下問題:
1.對未初始化內存的使用;
2.讀/寫釋放后的內存塊;
3.讀/寫超出malloc分配的內存塊;
4.讀/寫不適當的棧中內存塊;
5.內存泄漏,指向一塊內存的指針永遠丟失;
6.不正確的malloc/free或new/delete匹配;
7,memcpy()相關函數中的dst和src指針重疊。
一些常用的選項:
查考其幫助 valgrind -h or info valgrind
我們通過例子看一下它的具體使用。我們構造一個存在內存泄漏的C程序,如下:
我們得到如下錯誤信息:
我們可以很清楚地看出,分配和釋放了多少內存,有多少內存泄漏。
這對我們查找內存泄漏十分方便。然后我們重新編譯程序并綁定調試器:
Artistic Style Eclipse Plugin 是一個用來對C/C++代碼進行格式化的 Eclipse 插件,可在 Eclipse CDT 環境中使用.可以用來定義基本的編碼格式風格,比如代碼縮進,在* +等運算符兩端加上空格的,不同模塊間添加空行
CppNcss復雜度檢查工具,可度量函數級,文件級,工程級的復雜度
總結:cppcheck與splint是靜態的代碼檢查工具,valgrind為動態的代碼檢查工具。主要檢查對象都是內存管理錯誤。valgrind由于前兩者,它得到更為豐富準確的信息。但是由于它提供了大量的信息,對于是否是bug的鑒定更為困難。ArtisticStyle Eclipse Plugin能在基本的代碼格式風格和規范上起到一定的幫助作用。