/man/manual.md

http://github.com/danmar/cppcheck · Markdown · 869 lines · 501 code · 368 blank · 0 comment · 0 complexity · e0f20ed4ba1c889e01da3900ff763219 MD5 · raw file

  1. ---
  2. title: Cppcheck manual
  3. subtitle: Version 2.0
  4. author: Cppcheck team
  5. lang: en
  6. documentclass: report
  7. ---
  8. # Introduction
  9. Cppcheck is an analysis tool for C/C++ code. It provides unique code analysis to detect bugs and focuses on detecting undefined behaviour and dangerous coding constructs. The goal is to detect only real errors in the code (i.e. have very few false positives). Cppcheck is designed to be able to analyze your C/C++ code even if it has non-standard syntax (common in embedded projects).
  10. Supported code and platforms:
  11. - You can check non-standard code that contains various compiler extensions, inline assembly code, etc.
  12. - Cppcheck should be compilable by any C++ compiler that handles the latest C++ standard.
  13. - Cppcheck should work on any platform that has sufficient CPU and memory.
  14. Please understand that there are limits of Cppcheck. Cppcheck is rarely wrong about reported errors. But there are
  15. many bugs that it doesn't detect.
  16. You will find more bugs in your software by testing your software carefully, than by using Cppcheck. You will find
  17. more bugs in your software by instrumenting your software, than by using Cppcheck. But Cppcheck can still detect some
  18. of the bugs that you miss when testing and instrumenting your software.
  19. # Getting started
  20. ## GUI
  21. It is not required but creating a new project file is a good first step. There are a few options you can tweak to get
  22. good results.
  23. In the project settings dialog, the first option you see is "Import project". It is recommended that you use this
  24. feature if you can. Cppcheck can import:
  25. - Visual studio solution / project
  26. - Compile database (can be generated from cmake/qbs/etc build files)
  27. - Borland C++ Builder 6
  28. When you have filled out the project settings and click on OK; the Cppcheck analysis will start.
  29. ## Command line
  30. ### First test
  31. Here is a simple code
  32. int main()
  33. {
  34. char a[10];
  35. a[10] = 0;
  36. return 0;
  37. }
  38. If you save that into file1.c and execute:
  39. cppcheck file1.c
  40. The output from cppcheck will then be:
  41. Checking file1.c...
  42. [file1.c:4]: (error) Array 'a[10]' index 10 out of bounds
  43. ### Checking all files in a folder
  44. Normally a program has many source files. And you want to check them all. Cppcheck can check all source files in a directory:
  45. cppcheck path
  46. If "path" is a folder then cppcheck will recursively check all source files in this folder.
  47. Checking path/file1.cpp...
  48. 1/2 files checked 50% done
  49. Checking path/file2.cpp...
  50. 2/2 files checked 100% done
  51. ### Check files manually or use project file
  52. With Cppcheck you can check files manually, by specifying files/paths to check and settings. Or you can use a project file (cmake/visual studio/etc).
  53. We don't know which approach (project file or manual configuration) will give you the best results. It is recommended that you try both. It is possible that you will get different results so that to find most bugs you need to use both approaches.
  54. Later chapters will describe this in more detail.
  55. ### Check files matching a given file filter
  56. With `--file-filter=<str>` you can set a file filter and only those files matching the filter will be checked.
  57. For example: if you want to check only those files and folders starting from a subfolder src/ that start with "test" you have to type:
  58. cppcheck src/ --file-filter=src/test*
  59. Cppcheck first collects all files in src/ and will apply the filter after that. So the filter must start with the given start folder.
  60. ### Excluding a file or folder from checking
  61. To exclude a file or folder, there are two options. The first option is to only provide the paths and files you want to check.
  62. cppcheck src/a src/b
  63. All files under src/a and src/b are then checked.
  64. The second option is to use -i, with it you specify files/paths to ignore. With this command no files in src/c are checked:
  65. cppcheck -isrc/c src
  66. This option is only valid when supplying an input directory. To ignore multiple directories supply the -i multiple times. The following command ignores both the src/b and src/c directories.
  67. cppcheck -isrc/b -isrc/c
  68. ### Clang parser
  69. By default Cppcheck uses an internal C/C++ parser. However it is possible to use the Clang parser instead.
  70. Install `clang`. Then use Cppcheck option `--clang`.
  71. Technically, Cppcheck will execute `clang` with its `-ast-dump` option. The Clang output is then imported and converted into our normal Cppcheck format. And then normal Cppcheck analysis is performed on that.
  72. ## Severities
  73. The possible severities for messages are:
  74. **error**
  75. used when bugs are found
  76. **warning**
  77. suggestions about defensive programming to prevent bugs
  78. **style**
  79. stylistic issues related to code cleanup (unused functions, redundant code, constness, and such)
  80. **performance**
  81. Suggestions for making the code faster. These suggestions are only based on common knowledge. It is not certain you'll get any measurable difference in speed by fixing these messages.
  82. **portability**
  83. portability warnings. 64-bit portability. code might work different on different compilers. etc.
  84. **information**
  85. Configuration problems. The recommendation is to only enable these during configuration.
  86. # Importing project
  87. You can import some project files and build configurations into Cppcheck.
  88. ## Cppcheck GUI project
  89. You can import and use Cppcheck GUI project files in the command line tool:
  90. cppcheck --project=foobar.cppcheck
  91. The Cppcheck GUI has a few options that are not available in the command line directly. To use these options you can import a GUI project file. We want to keep the command line tool usage simple and limit the options by intention.
  92. To ignore certain folders in the project you can use `-i`. This will skip analysis of source files in the `foo` folder.
  93. cppcheck --project=foobar.cppcheck -ifoo
  94. ## CMake
  95. Generate a compile database:
  96. cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .
  97. The file `compile_commands.json` is created in the current folder. Now run Cppcheck like this:
  98. cppcheck --project=compile_commands.json
  99. To ignore certain folders you can use `-i`. This will skip analysis of source files in the `foo` folder.
  100. cppcheck --project=compile_commands.json -ifoo
  101. ## Visual Studio
  102. You can run Cppcheck on individual project files (\*.vcxproj) or on a whole solution (\*.sln)
  103. Running Cppcheck on an entire Visual Studio solution:
  104. cppcheck --project=foobar.sln
  105. Running Cppcheck on a Visual Studio project:
  106. cppcheck --project=foobar.vcxproj
  107. Both options will analyze all available configurations in the project(s).
  108. Limiting on a single configuration:
  109. cppcheck --project=foobar.sln "--project-configuration=Release|Win32"
  110. In the `Cppcheck GUI` you have the choice to only analyze a single debug configuration. If you want to use this choice on the command line then create a `Cppcheck GUI` project with this activated and then import the GUI project file on the command line.
  111. To ignore certain folders in the project you can use `-i`. This will skip analysis of source files in the `foo` folder.
  112. cppcheck --project=foobar.vcxproj -ifoo
  113. ## C++ Builder 6
  114. Running Cppcheck on a C++ Builder 6 project:
  115. cppcheck --project=foobar.bpr
  116. To ignore certain folders in the project you can use `-i`. This will skip analysis of source files in the `foo` folder.
  117. cppcheck --project=foobar.bpr -ifoo
  118. ## Other
  119. If you can generate a compile database then it's possible to import that in Cppcheck.
  120. In Linux you can use for instance the `bear` (build ear) utility to generate a compile database from arbitrary build tools:
  121. bear make
  122. # Platform
  123. You should use a platform configuration that match your target.
  124. By default Cppcheck uses native platform configuration that works well if your code is compiled and executed locally.
  125. Cppcheck has builtin configurations for Unix and Windows targets. You can easily use these with the `--platform` command line flag.
  126. You can also create your own custom platform configuration in a XML file. Here is an example:
  127. <?xml version="1"?>
  128. <platform>
  129. <char_bit>8</char_bit>
  130. <default-sign>signed</default-sign>
  131. <sizeof>
  132. <short>2</short>
  133. <int>4</int>
  134. <long>4</long>
  135. <long-long>8</long-long>
  136. <float>4</float>
  137. <double>8</double>
  138. <long-double>12</long-double>
  139. <pointer>4</pointer>
  140. <size_t>4</size_t>
  141. <wchar_t>2</wchar_t>
  142. </sizeof>
  143. </platform>
  144. # Preprocessor Settings
  145. If you use `--project` then Cppcheck will use the preprocessor settings from the imported project. Otherwise you'll probably want to configure the include paths, defines, etc.
  146. ## Defines
  147. Here is a file that has 2 preprocessor configurations (with A defined and without A defined):
  148. #ifdef A
  149. x = y;
  150. #else
  151. x = z;
  152. #endif
  153. By default Cppcheck will check all preprocessor configurations (except those that have #error in them). So the above code will by default be analyzed both with `A` defined and without `A` defined.
  154. You can use `-D` to change this. When you use `-D`, cppcheck will by default only check the given configuration and nothing else. This is how compilers work. But you can use `--force` or `--max-configs` to override the number of configurations.
  155. Check all configurations:
  156. cppcheck file.c
  157. Only check the configuration A:
  158. cppcheck -DA file.c
  159. Check all configurations when macro A is defined
  160. cppcheck -DA --force file.c
  161. Another useful flag might be `-U`. It tells Cppcheck that a macro is not defined. Example usage:
  162. cppcheck -UX file.c
  163. That will mean that X is not defined. Cppcheck will not check what happens when X is defined.
  164. ## Include paths
  165. To add an include path, use `-I`, followed by the path.
  166. Cppcheck's preprocessor basically handles includes like any other preprocessor. However, while other preprocessors stop working when they encounter a missing header, cppcheck will just print an information message and continues parsing the code.
  167. The purpose of this behaviour is that cppcheck is meant to work without necessarily seeing the entire code. Actually, it is recommended to not give all include paths. While it is useful for cppcheck to see the declaration of a class when checking the implementation of its members, passing standard library headers is highly discouraged because it will result in worse results and longer checking time. For such cases, .cfg files (see below) are the better way to provide information about the implementation of functions and types to cppcheck.
  168. # Suppressions
  169. If you want to filter out certain errors you can suppress these.
  170. Please note that if you see a false positive then we (the Cppcheck team) want that you report it so we can fix it.
  171. ## Plain text suppressions
  172. You can suppress certain types of errors. The format for such a suppression is one of:
  173. [error id]:[filename]:[line]
  174. [error id]:[filename2]
  175. [error id]
  176. The `error id` is the id that you want to suppress. The easiest way to get it is to use the --template=gcc command line flag. The id is shown in brackets.
  177. The filename may include the wildcard characters \* or ?, which match any sequence of characters or any single character respectively. It is recommended that you use "/" as path separator on all operating systems. The filename must match the filename in the reported warning exactly. For instance, if the warning contains a relative path then the suppression must match that relative path.
  178. ## Command line suppression
  179. The `--suppress=` command line option is used to specify suppressions on the command line. Example:
  180. cppcheck --suppress=memleak:src/file1.cpp src/
  181. ## Suppressions in a file
  182. You can create a suppressions file. Example:
  183. // suppress memleak and exceptNew errors in the file src/file1.cpp
  184. memleak:src/file1.cpp
  185. exceptNew:src/file1.cpp
  186. // suppress all uninitvar errors in all files
  187. uninitvar
  188. Note that you may add empty lines and comments in the suppressions file.
  189. You can use the suppressions file like this:
  190. cppcheck --suppressions-list=suppressions.txt src/
  191. ## XML suppressions
  192. You can specify suppressions in a XML file. Example file:
  193. <?xml version="1.0"?>
  194. <suppressions>
  195. <suppress>
  196. <id>uninitvar</id>
  197. <fileName>src/file1.c</fileName>
  198. <lineNumber>10</lineNumber>
  199. <symbolName>var</symbolName>
  200. </suppress>
  201. </suppressions>
  202. The XML format is extensible and may be extended with further attributes in the future.
  203. You can use the suppressions file like this:
  204. cppcheck --suppress-xml=suppressions.xml src/
  205. ## Inline suppressions
  206. Suppressions can also be added directly in the code by adding comments that contain special keywords. Before adding such comments, consider that the code readability is sacrificed a little.
  207. This code will normally generate an error message:
  208. void f() {
  209. char arr[5];
  210. arr[10] = 0;
  211. }
  212. The output is:
  213. cppcheck test.c
  214. [test.c:3]: (error) Array 'arr[5]' index 10 out of bounds
  215. To activate inline suppressions:
  216. cppcheck --inline-suppr test.c
  217. ### Format
  218. You can suppress a warning `aaaa` with:
  219. // cppcheck-suppress aaaa
  220. Suppressing multiple ids in one comment by using []:
  221. // cppcheck-suppress [aaaa, bbbb]
  222. ### Comment before code or on same line
  223. The comment can be put before the code or at the same line as the code;
  224. Before the code:
  225. void f() {
  226. char arr[5];
  227. // cppcheck-suppress arrayIndexOutOfBounds
  228. arr[10] = 0;
  229. }
  230. Or at the same line as the code:
  231. void f() {
  232. char arr[5];
  233. arr[10] = 0; // cppcheck-suppress arrayIndexOutOfBounds
  234. }
  235. ### Multiple suppressions
  236. For a line of code there might be several warnings you want to suppress.
  237. There are several options;
  238. Using 2 suppression comments before code:
  239. void f() {
  240. char arr[5];
  241. // cppcheck-suppress arrayIndexOutOfBounds
  242. // cppcheck-suppress zerodiv
  243. arr[10] = arr[10] / 0;
  244. }
  245. Using 1 suppression comment before the code:
  246. void f() {
  247. char arr[5];
  248. // cppcheck-suppress[arrayIndexOutOfBounds,zerodiv]
  249. arr[10] = arr[10] / 0;
  250. }
  251. Suppression comment on the same line as the code:
  252. void f() {
  253. char arr[5];
  254. arr[10] = arr[10] / 0; // cppcheck-suppress[arrayIndexOutOfBounds,zerodiv]
  255. }
  256. ### Symbol name
  257. You can specify that the inline suppression only applies to a specific symbol:
  258. // cppcheck-suppress aaaa symbolName=arr
  259. Or
  260. // cppcheck-suppress[aaaa symbolName=arr, bbbb]
  261. ### Comment about suppression
  262. You can write comments about a suppression like so:
  263. // cppcheck-suppress[warningid] some comment
  264. // cppcheck-suppress warningid ; some comment
  265. // cppcheck-suppress warningid // some comment
  266. # XML output
  267. Cppcheck can generate output in XML format. Use `--xml` to enable this format.
  268. A sample command to check a file and output errors in the XML format:
  269. cppcheck --xml file1.cpp
  270. Here is a sample report:
  271. <?xml version="1.0" encoding="UTF-8"?>
  272. <results version="2">
  273. <cppcheck version="1.66"/>
  274. <errors>
  275. <error id="someError" severity="error" msg="short error text"
  276. verbose="long error text" inconclusive="true" cwe="312">
  277. <location file0="file.c" file="file.h" line="1"/>
  278. </error>
  279. </errors>
  280. </results>
  281. ## The `<error>` element
  282. Each error is reported in a `<error>` element. Attributes:
  283. **id**
  284. id of error. These are always valid symbolnames.
  285. **severity**
  286. error/warning/style/performance/portability/information
  287. **msg**
  288. the error message in short format
  289. **verbose**
  290. the error message in long format
  291. **inconclusive**
  292. this attribute is only used when the error message is inconclusive
  293. **cwe**
  294. CWE ID for the problem. This attribute is only used when the CWE ID for the message is known.
  295. ## The `<location>` element
  296. All locations related to an error are listed with `<location>` elements. The primary location is listed first.
  297. Attributes:
  298. **file**
  299. filename. both relative and absolute paths are possible.
  300. **file0**
  301. name of the source file (optional)
  302. **line**
  303. line number
  304. **info**
  305. short information for each location (optional)
  306. # Reformatting the text output
  307. If you want to reformat the output so it looks different you can use templates.
  308. ## Predefined output formats
  309. To get Visual Studio compatible output you can use --template=vs:
  310. cppcheck --template=vs samples/arrayIndexOutOfBounds/bad.c
  311. This output will look like this:
  312. Checking samples/arrayIndexOutOfBounds/bad.c ...
  313. samples/arrayIndexOutOfBounds/bad.c(6): error: Array 'a[2]' accessed at index 2, which is out of bounds.
  314. To get gcc compatible output you can use --template=gcc:
  315. cppcheck --template=gcc samples/arrayIndexOutOfBounds/bad.c
  316. The output will look like this:
  317. Checking samples/arrayIndexOutOfBounds/bad.c ...
  318. samples/arrayIndexOutOfBounds/bad.c:6:6: warning: Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]
  319. a[2] = 0;
  320. ^
  321. ## User defined output format (single line)
  322. You can write your own pattern. For instance, to get warning messages that are formatted like old gcc such format can be used:
  323. cppcheck --template="{file}:{line}: {severity}: {message}" samples/arrayIndexOutOfBounds/bad.c
  324. The output will look like this:
  325. Checking samples/arrayIndexOutOfBounds/bad.c ...
  326. samples/arrayIndexOutOfBounds/bad.c:6: error: Array 'a[2]' accessed at index 2, which is out of bounds.
  327. A comma separated format:
  328. cppcheck --template="{file},{line},{severity},{id},{message}" samples/arrayIndexOutOfBounds/bad.c
  329. The output will look like this:
  330. Checking samples/arrayIndexOutOfBounds/bad.c ...
  331. samples/arrayIndexOutOfBounds/bad.c,6,error,arrayIndexOutOfBounds,Array 'a[2]' accessed at index 2, which is out of bounds.
  332. ## User defined output format (multi line)
  333. Many warnings have multiple locations. Example code:
  334. void f(int *p)
  335. {
  336. *p = 3; // line 3
  337. }
  338. int main()
  339. {
  340. int *p = 0; // line 8
  341. f(p); // line 9
  342. return 0;
  343. }
  344. There is a possible null pointer dereference at line 3. Cppcheck can show how it came to that conclusion by showing extra location information. You need to use both --template and --template-location at the command line.
  345. Example command:
  346. cppcheck --template="{file}:{line}: {severity}: {message}\n{code}" --template-location="{file}:{line}: note: {info}\n{code}" multiline.c
  347. The output from Cppcheck is:
  348. Checking multiline.c ...
  349. multiline.c:3: warning: Possible null pointer dereference: p
  350. *p = 3;
  351. ^
  352. multiline.c:8: note: Assignment 'p=0', assigned value is 0
  353. int *p = 0;
  354. ^
  355. multiline.c:9: note: Calling function 'f', 1st argument 'p' value is 0
  356. f(p);
  357. ^
  358. multiline.c:3: note: Null pointer dereference
  359. *p = 3;
  360. ^
  361. The first line in the warning is formatted by the --template format.
  362. The other lines in the warning are formatted by the --template-location format.
  363. ### Format specifiers for --template
  364. The available specifiers for --template are:
  365. **{file}**
  366. File name
  367. **{line}**
  368. Line number
  369. **{column}**
  370. Column number
  371. **{callstack}**
  372. Write all locations. Each location is written in [{file}:{line}] format and the locations are separated by ->. For instance it might look like: [multiline.c:8] -> [multiline.c:9] -> [multiline.c:3]
  373. **{inconclusive:text}**
  374. If warning is inconclusive then the given text is written. The given text can be any arbitrary text that does not contain }. Example: {inconclusive:inconclusive,}
  375. **{severity}**
  376. error/warning/style/performance/portability/information
  377. **{message}**
  378. The warning message
  379. **{id}**
  380. Warning id
  381. **{code}**
  382. The real code.
  383. **\\t**
  384. Tab
  385. **\\n**
  386. Newline
  387. **\\r**
  388. Carriage return
  389. ### Format specifiers for --template-location
  390. The available specifiers for `--template-location` are:
  391. **{file}**
  392. File name
  393. **{line}**
  394. Line number
  395. **{column}**
  396. Column number
  397. **{info}**
  398. Information message about current location
  399. **{code}**
  400. The real code.
  401. **\\t**
  402. Tab
  403. **\\n**
  404. Newline
  405. **\\r**
  406. Carriage return
  407. # Addons
  408. Addons are scripts that analyses Cppcheck dump files to check compatibility with secure coding standards and to locate various issues.
  409. Cppcheck is distributed with a few addons which are listed below.
  410. ## Supported addons
  411. ### cert.py
  412. [cert.py](https://github.com/danmar/cppcheck/blob/master/addons/cert.py) checks for compliance with the safe programming standard [SEI CERT](http://www.cert.org/secure-coding/).
  413. ### misra.py
  414. [misra.py](https://github.com/danmar/cppcheck/blob/master/addons/misra.py) is used to verify compliance with MISRA C 2012 - a proprietary set of guidelines to avoid such questionable code, developed for embedded systems.
  415. Since this standard is proprietary, cppcheck does not display error text by specifying only the number of violated rules (for example, [c2012-21.3]). If you want to display full texts for violated rules, you will need to create a text file containing MISRA rules, which you will have to pass when calling the script with `--rule-texts` key. Some examples of rule texts files available in [tests directory](https://github.com/danmar/cppcheck/blob/master/addons/test/misra/).
  416. You can also suppress some unwanted rules using `--suppress-rules` option. Suppressed rules should be set as comma-separated listed, for example: `--suppress-rules 21.1,18.7`. The full list of supported rules is available on [Cppcheck](http://cppcheck.sourceforge.net/misra.php) home page.
  417. ### y2038.py
  418. [y2038.py](https://github.com/danmar/cppcheck/blob/master/addons/y2038.py) checks Linux system for [year 2038 problem](https://en.wikipedia.org/wiki/Year_2038_problem) safety. This required [modified environment](https://github.com/3adev/y2038). See complete description [here](https://github.com/danmar/cppcheck/blob/master/addons/doc/y2038.txt).
  419. ### threadsafety.py
  420. [threadsafety.py](https://github.com/danmar/cppcheck/blob/master/addons/threadsafety.py) analyse Cppcheck dump files to locate thread safety issues like static local objects used by multiple threads.
  421. ## Running Addons
  422. Addons could be run through Cppcheck command line utility as follows:
  423. cppcheck --addon=misra.py somefile.c
  424. This will launch all Cppcheck checks and additionally calls specific checks provided by selected addon.
  425. Some addons need extra arguments. You can configure how you want to execute an addon in a json file. For example put this in misra.json:
  426. {
  427. "script": "misra.py",
  428. "args": [
  429. "--rule-texts=misra.txt",
  430. "--suppress-rules 17.3,21.12"
  431. ]
  432. }
  433. And then the configuration can be executed on the cppcheck command line:
  434. cppcheck --addon=misra.json somefile.c
  435. By default Cppcheck would search addon at standard path which was specified in installation process. You also can set this path directly, for example:
  436. cppcheck --addon=/opt/cppcheck/configurations/my_misra.json somefile.c
  437. This allows you create and manage multiple configuration files for different projects.
  438. # Library configuration
  439. When external libraries are used, such as WinAPI, POSIX, gtk, Qt, etc, Cppcheck doesn't know how the external functions behave. Cppcheck then fails to detect various problems such as leaks, buffer overflows, possible null pointer dereferences, etc. But this can be fixed with configuration files.
  440. Cppcheck already contains configurations for several libraries. They can be loaded as described below. Note that the configuration for the standard libraries of C and C++, std.cfg, is always loaded by cppcheck. If you create or update a configuration file for a popular library, we would appreciate if you upload it to us.
  441. ## Using your own custom .cfg file
  442. You can create and use your own .cfg files for your projects. Use `--check-library` and `--enable=information` to get hints about what you should configure.
  443. You can use the `Library Editor` in the `Cppcheck GUI` to edit configuration files. It is available in the `View` menu.
  444. The .cfg file format is documented in the `Reference: Cppcheck .cfg format` (http://cppcheck.sf.net/reference-cfg-format.pdf) document.
  445. # HTML Report
  446. You can convert the XML output from cppcheck into a HTML report. You'll need Python and the pygments module (<http://pygments.org/)> for this to work. In the Cppcheck source tree there is a folder htmlreport that contains a script that transforms a Cppcheck XML file into HTML output.
  447. This command generates the help screen:
  448. htmlreport/cppcheck-htmlreport -h
  449. The output screen says:
  450. Usage: cppcheck-htmlreport [options]
  451. Options:
  452. -h, --help show this help message and exit
  453. --file=FILE The cppcheck xml output file to read defects from.
  454. Default is reading from stdin.
  455. --report-dir=REPORT_DIR
  456. The directory where the html report content is written.
  457. --source-dir=SOURCE_DIR
  458. Base directory where source code files can be found.
  459. An example usage:
  460. ./cppcheck gui/test.cpp --xml 2> err.xml
  461. htmlreport/cppcheck-htmlreport --file=err.xml --report-dir=test1 --source-dir=.
  462. # Bug hunting
  463. If you want to detect most bugs and can accept false alarms then Cppcheck has analysis for that.
  464. This analysis is "soundy"; it should diagnose most bugs reported in CVEs and from dynamic analysis.
  465. You have to expect false alarms. However Cppcheck tries to limit false alarms. The purpose of the data flow analysis is to limit false alarms.
  466. Some possible use cases;
  467. * you are writing new code and want to ensure it is safe.
  468. * you are reviewing code and want to get hints about possible UB.
  469. * you need extra help troubleshooting a weird bug.
  470. * you want to check if a release candidate is safe.
  471. The intention is that this will be used primarily in the GUI.
  472. ## Activate this analysis
  473. On the command line you can use `--bug-hunting` however then you can't configure contracts (see below).
  474. In the GUI goto the project dialog. In the `Analysis` tab there is a check box for `Bug hunting`.
  475. ## Cppcheck contracts
  476. To handle false alarms and improve the analysis you are encouraged to use contracts.
  477. You can use Cppcheck contracts both for C and C++ code.
  478. Example code:
  479. int foo(int x)
  480. {
  481. return 100 / x;
  482. }
  483. A division by zero would not be impossible so Cppcheck will diagnose it:
  484. [test1.cpp:3] (error) There is division, cannot determine that there can't be a division by zero. [bughuntingDivByZero]
  485. This Cppcheck contract will silence that warning:
  486. function: foo(x)
  487. expects: x > 0
  488. That contract will improve the intra procedural analysis. Every time `foo` is called it will be checked that the contract is satisfied:
  489. void bar(int x)
  490. {
  491. foo(x);
  492. }
  493. Cppcheck will warn:
  494. [test1.cpp:10] (error) Function 'foo' is called, can not determine that its contract 'x>0' is always met. [bughuntingFunctionCall]
  495. ## Adding a contract in the GUI
  496. There are two ways:
  497. * Open the "Contracts" tab at the bottom of the screen. Find the function in the listbox and double click on it.
  498. * Right click on a warning and click on "Edit contract.." in the popup menu. This popup menu item is only available if the warning is not inconclusive.
  499. ## Incomplete analysis
  500. The data flow analysis can analyze simple functions completely but complex functions are not analyzed completely (yet). The data flow analysis will be continously improved in the future but it will never be perfect.
  501. It is likely that you will get false alarms caused by incomplete data flow analysis. Unfortunately it is unlikely that such false alarms can be fixed by contracts.