Manual
User Manual:
Open the PDF directly: View PDF .
Page Count: 36
Download | ![]() |
Open PDF In Browser | View PDF |
Cppcheck 1.85 Cppcheck 1.85 Table of Contents 1. Introduction .................................................................................................................... 1 2. Getting started (GUI) ....................................................................................................... 2 New Project ............................................................................................................... 2 New Project - Paths and Defines ................................................................................... 2 New Project - Project .................................................................................................. 2 New Project - Addons ................................................................................................. 2 Analyze ..................................................................................................................... 2 3. Getting started (command line) .......................................................................................... 3 First test .................................................................................................................... 3 Checking all files in a folder ........................................................................................ 3 Check files manually or use project file .......................................................................... 3 Excluding a file or folder from checking ........................................................................ 4 Severities ................................................................................................................... 4 Enable messages ......................................................................................................... 4 Inconclusive checks ............................................................................................. 5 Saving results in file ................................................................................................... 5 Multithreaded checking ................................................................................................ 5 Platform .................................................................................................................... 5 4. Project ........................................................................................................................... 7 CMake ...................................................................................................................... 7 Visual Studio ............................................................................................................. 7 5. Preprocessor settings ........................................................................................................ 8 Defines ..................................................................................................................... 8 Include paths .............................................................................................................. 8 6. XML output ................................................................................................................... 9 Theelement .................................................................................................... 9 The element ............................................................................................... 9 7. Reformatting the output .................................................................................................. 10 Predefined output formats ........................................................................................... 10 User defined output format (single line) ........................................................................ 10 User defined output format (multi line) ......................................................................... 10 Format specifiers for --template ................................................................................... 11 Format specifiers for --template-location ....................................................................... 12 8. Misra ........................................................................................................................... 13 Requirements ............................................................................................................ 13 MISRA Text file ....................................................................................................... 13 9. Suppressions ................................................................................................................. 14 Plain text suppressions ............................................................................................... 14 Command line suppression ................................................................................. 14 Listing suppressions in a file ............................................................................... 14 XML suppressions ..................................................................................................... 14 Inline suppressions .................................................................................................... 15 10. Library configuration .................................................................................................... 16 Using your own custom .cfg file .................................................................................. 16 Memory/resource leaks .............................................................................................. 16 alloc and dealloc ............................................................................................... 16 leak-ignore and use ........................................................................................... 17 Function behaviour .................................................................................................... 17 Function arguments ........................................................................................... 18 noreturn ........................................................................................................... 22 use-retval ......................................................................................................... 23 iii Cppcheck 1.85 11. 12. 13. 14. pure and const .................................................................................................. Example configuration for strcpy() ....................................................................... define ...................................................................................................................... podtype ................................................................................................................... container .................................................................................................................. Rules ......................................................................................................................... ............................................................................................................... ................................................................................................................. ........................................................................................................................ ................................................................................................................ .............................................................................................................. Cppcheck addons ......................................................................................................... Using Cppcheck addons ............................................................................................. Where to find some Cppcheck addons .................................................................. Writing Cppcheck addons ........................................................................................... Example 1 - print all tokens ................................................................................ Example 2 - List all functions ............................................................................. Example 3 - List all classes ................................................................................ HTML report .............................................................................................................. Graphical user interface ................................................................................................ Introduction .............................................................................................................. Check source code .................................................................................................... Inspecting results ...................................................................................................... Settings ................................................................................................................... Project files .............................................................................................................. iv 24 24 25 25 26 27 27 27 27 28 28 29 29 29 29 30 30 30 31 32 32 32 32 32 32 Chapter 1. Introduction Cppcheck is an analysis tool for C/C++ code. Unlike C/C++ compilers and many other analysis tools, it doesn't detect syntax errors. Instead, Cppcheck detects the types of bugs that the compilers normally fail to detect. The goal is no false positives. Supported code and platforms: • You can check non-standard code that includes various compiler extensions, inline assembly code, etc. • Cppcheck should be compilable by any C++ compiler that handles the latest C++ standard. • Cppcheck should work on any platform that has sufficient CPU and memory. Please understand that there are limits of Cppcheck. Cppcheck is rarely wrong about reported errors. But there are many bugs that it doesn't detect. You will find more bugs in your software by testing your software carefully, than by using Cppcheck. You will find more bugs in your software by instrumenting your software, than by using Cppcheck. But Cppcheck can still detect some of the bugs that you miss when testing and instrumenting your software. 1 Chapter 2. Getting started (GUI) Start the GUI. New Project It is not required but creating a new project file is a good first step. You do so through File and New project file. New Project - Paths and Defines What kind of project do you have? If it is a Visual Studio project or if you can generate a compile database (cmake/qbs/etc), then you can import the project. Otherwise you can configure the paths and defines manually. In this screenshot below, a Visual Studio project file is imported: New Project - Project In the Project tab it is highly recommended that a Cppcheck build dir is configured. This will be used by Cppcheck to store various analysis information. It gives you whole program analysis, incremental analysis, statistics, etc. Each project should have its own unique build dir. In the screenshot below the build dir is configured as cppcheck-build-dir. The path is relative to the project file. You should also choose all the libraries that you use. In the screenshot below the microsoft_sal and windows libraries are selected. You can read more about libraries in this manual. New Project - Addons We skip the Exclude and Suppressions tabs now, they can be used later to tweak the results. In the Addons tab you can add extra analysis. The addons require python. Analyze Click the OK button in the dialog. Analysis will start immediately. All warnings are activated and therefore it is pretty noisy. There are likely various warnings that you don't care about. You can fix that easily, right click on messages and choose Hide or Suppress. Hiding messages is not permanent, they will be shown after next analysis. Suppressing messages is permanent, suppressed ids are stored in the project file and those will not be shown again. 2 Chapter 3. Getting started (command line) First test Here is a simple code int main() { char a[10]; a[10] = 0; return 0; } If you save that into file1.c and execute: cppcheck file1.c The output from cppcheck will then be: Checking file1.c... [file1.c:4]: (error) Array 'a[10]' index 10 out of bounds Checking all files in a folder Normally a program has many source files. And you want to check them all. Cppcheck can check all source files in a directory: cppcheck path If "path" is a folder then cppcheck will recursively check all source files in this folder. Checking path/file1.cpp... 1/2 files checked 50% done Checking path/file2.cpp... 2/2 files checked 100% done Check files manually or use project file 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). Using the project file is quicker since it requires very little configuration from you. Checking files manually gives you better control of the analysis. We don't know which approach 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. Later chapters will describe this in more detail. 3 Getting started (command line) Excluding a file or folder from checking 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. cppcheck src/a src/b All files under src/a and src/b are then checked. 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: cppcheck -isrc/c src This option does not currently work with the --project option and 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. cppcheck -isrc/b -isrc/c Severities The possible severities for messages are: error used when bugs are found warning suggestions about defensive programming to prevent bugs style stylistic issues related to code cleanup (unused functions, redundant code, constness, and such) performance 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. portability portability warnings. 64-bit portability. code might work different on different compilers. etc. information Configuration problems. The recommendation is to only enable these during configuration. Enable messages By default only error messages are shown. Through the --enable command more checks can be enabled. # enable warning messages cppcheck --enable=warning file.c # enable performance messages cppcheck --enable=performance file.c # enable information messages cppcheck --enable=information file.c 4 Getting started (command line) # For historical reasons, --enable=style enables warning, performance, # portability and style messages. These are all reported as "style" when # using the old xml format. cppcheck --enable=style file.c # enable warning and performance messages cppcheck --enable=warning,performance file.c # enable unusedFunction checking. This is not enabled by --enable=style # because it doesn't work well on libraries. cppcheck --enable=unusedFunction file.c # enable all messages cppcheck --enable=all Please note that --enable=unusedFunction should only be used when the whole program is scanned. Therefore, --enable=all should also only be used when the whole program is scanned. The reason is that the unusedFunction checking will warn if a function is not called. There will be noise if function calls are not seen. Inconclusive checks By default Cppcheck only writes error messages if it is certain. With --inconclusive error messages will also be written when the analysis is inconclusive. cppcheck --inconclusive path This can of course cause false warnings, it might be reported that there are bugs even though there are not. Only use this command if false warnings are acceptable. Saving results in file Many times you will want to save the results in a file. You can use the normal shell redirection for piping error output to a file. cppcheck file1.c 2> err.txt Multithreaded checking The option -j is used to specify the number of threads you want to use. For example, to use 4 threads to check the files in a folder: cppcheck -j 4 path Please note that this will disable unusedFunction checking. Platform You should use a platform configuration that match your target. By default Cppcheck uses native platform configuration that works well if your code is compiled and executed locally. 5 Getting started (command line) Cppcheck has builtin configurations for unix and windows targets. You can easily use these with the --platform command line flag. You can also create your own custom platform configuration in a xml file. Here is an example: 6 Chapter 4. Project When you use CMake or Visual Studio you can use --project to analyse your project. It will give you quick and easy results. There is not much configuration you need to do. But it is hard to say if this will give you the best results, it is recommended that you try it and also try to analyse your source code without --project and see which option works best for you. CMake Cppcheck can understand compile databases. You can generate these with CMake. Example: $ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON . The file compile_commands.json is created in the current folder. Now run Cppcheck like this: $ cppcheck --project=compile_commands.json Visual Studio You can run Cppcheck on individual project files (*.vcxproj) or on a whole solution (*.sln) # run cppcheck on a whole solution $ cppcheck --project=foobar.sln # run cppcheck on a individual project $ cppcheck --project=foobar.vcxproj Please note that there is also a Visual Studio plugin that allows you to run cppcheck inside Visual Studio. 7 Chapter 5. Preprocessor settings If you use --project then Cppcheck will use the preprocessor settings from the project file. Otherwise you'll probably want to configure the include paths, defines etc. Defines Here is a file that has 2 configurations (with A defined and without A): #ifdef A x = y; #else x = z; #endif By default Cppcheck will check all preprocessor configurations (except those that have #error in them). So the above code will be analysed both when A is defined and when it is not. 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. # check all configurations cppcheck file.c # only check the configuration A cppcheck -DA file.c # check all configurations when macro A is defined cppcheck -DA --force file.c Another useful flag might be -U. It undefines a symbol. Example usage: cppcheck -UX file.c That will mean that X is not defined. Cppcheck will not check what happens when X is defined. Include paths To add an include path, use -I, followed by the path. 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. 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. 8 Chapter 6. XML output Cppcheck can generate output in XML format. Use --xml to enable this format. A sample command to check a file and output errors in the XML format: cppcheck --xml file1.cpp Here is a sample report: 8 signed 2 4 4 8 4 8 12 4 4 2 The element Each error is reported in a element. Attributes: id id of error. These are always valid symbolnames. severity either: error, warning, style, performance, portability or information msg the error message in short format verbose the error message in long format. inconclusive This attribute is only used when the message is inconclusive. cwe CWE ID for message. This attribute is only used when the CWE ID for the message is known. The element All locations related to an error is listed with elements. The primary location is listed first. Attributes: file filename. Both relative and absolute paths are possible file0 name of the source file (optional) line a number info short information message for each location (optional) 9 Chapter 7. Reformatting the output If you want to reformat the output so it looks different you can use templates. Predefined output formats To get Visual Studio compatible output you can use --template=vs: cppcheck --template=vs samples/arrayIndexOutOfBounds/bad.c This output will look like this: Checking samples/arrayIndexOutOfBounds/bad.c ... samples/arrayIndexOutOfBounds/bad.c(6): error: Array 'a[2]' accessed at index 2, wh To get gcc compatible output you can use --template=gcc: cppcheck --template=gcc samples/arrayIndexOutOfBounds/bad.c The output will look like this: Checking samples/arrayIndexOutOfBounds/bad.c ... samples/arrayIndexOutOfBounds/bad.c:6:6: warning: Array 'a[2]' accessed at index 2, a[2] = 0; ^ User defined output format (single line) You can write your own pattern. For instance, to get warning messages that are formatted like old gcc such format can be used: cppcheck --template="{file}:{line}: {severity}: {message}" samples/arrayIndexOutOfB The output will look like this: Checking samples/arrayIndexOutOfBounds/bad.c ... samples/arrayIndexOutOfBounds/bad.c:6: error: Array 'a[2]' accessed at index 2, whi A comma separated format: cppcheck --template="{file},{line},{severity},{id},{message}" samples/arrayIndexOut The output will look like this: Checking samples/arrayIndexOutOfBounds/bad.c ... samples/arrayIndexOutOfBounds/bad.c,6,error,arrayIndexOutOfBounds,Array 'a[2]' acce User defined output format (multi line) Many warnings have multiple locations. Example code: void f(int *p) { 10 Reformatting the output *p = 3; // line 3 int main() { int *p = 0; f(p); return 0; } // line 8 // line 9 } 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. Example command: cppcheck --template="{file}:{line}: {severity}: {message}\n{code}" --template-locat The output from Cppcheck is: Checking multiline.c ... multiline.c:3: warning: Possible null pointer dereference: p *p = 3; ^ multiline.c:8: note: Assignment 'p=0', assigned value is 0 int *p = 0; ^ multiline.c:9: note: Calling function 'f', 1st argument 'p' value is 0 f(p); ^ multiline.c:3: note: Null pointer dereference *p = 3; ^ The first line in the warning is formatted by the --template format. The other lines in the warning are formatted by the --template-location format. Format specifiers for --template The available specifiers for --template are: {file} File name {line} Line number {column} Column number {callstack} 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] {inconclusive:text} 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,} 11 Reformatting the output {severity} error/warning/style/performance/portability/information {message} The warning message {id} Warning id {code} The real code. \t Tab \t Newline \r Carriage return Format specifiers for --template-location The available specifiers for --template-location are: {file} File name {line} Line number {column} Column number {info} Information message about current location {code} The real code. \t Tab \t Newline \r Carriage return 12 Chapter 8. Misra Cppcheck has an addon that checks for MISRA C 2012 compliance. Requirements You need: • Python 2.X or 3.X • The MISRA C 2012 PDF. You can buy this from http://www.misra.org.uk (costs 15-20 pounds) MISRA Text file It is not allowed to publish the MISRA rule texts. Therefore the MISRA rule texts are not available directly in the addon. Instead, the addon can read the rule texts from a text file. If you copy/paste all text in "Appendix A Summary of guidelines" from the MISRA pdf, then you have all the rule texts. If you have installed xpdf, such text file can be generated on the command line (using pdftotext that is included in xpdf): pdftotext misra-c-2012.pdf output.txt The output might not be 100% perfect so you might need to make minor tweaks manually. Other pdf-to-text utilities might work also. To create the text file manually, copy paste Appendix A "Summary of guidelines" from the MISRA PDF. Format: Appendix A Summary of guidelines Rule 1.1 Rule text Rule 1.2 Rule text ... Rules that you want to disable does not need to have a rule text. Rules that don't have rule text will be suppressed by the addon. 13 Chapter 9. Suppressions If you want to filter out certain errors you can suppress these. Plain text suppressions You can suppress certain types of errors. The format for such a suppression is one of: [error id]:[filename]:[line] [error id]:[filename2] [error id] The error id is the id that you want to suppress. The easiest way to get it is to use the --xml command line flag. Copy and paste the id string from the XML output. This may be * to suppress all warnings (for a specified file or files). 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. Command line suppression The --suppress= command line option is used to specify suppressions on the command line. Example: cppcheck --suppress=memleak:src/file1.cpp src/ Listing suppressions in a file You can create a suppressions file. Example: // suppress memleak and exceptNew errors in the file src/file1.cpp memleak:src/file1.cpp exceptNew:src/file1.cpp // suppress all uninitvar errors in all files uninitvar Note that you may add empty lines and comments in the suppressions file. You can use the suppressions file like this: cppcheck --suppressions-list=suppressions.txt src/ XML suppressions You can specify suppressions in a XML file. Example file: The xml format is extensible and may be extended with further attributes in the future. Inline suppressions 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. This code will normally generate an error message: void f() { char arr[5]; arr[10] = 0; } The output is: # cppcheck test.c Checking test.c... [test.c:3]: (error) Array 'arr[5]' index 10 out of bounds To suppress the error message, a comment can be added: void f() { char arr[5]; // cppcheck-suppress arrayIndexOutOfBounds arr[10] = 0; } Now the --inline-suppr flag can be used to suppress the warning. No error is reported when invoking cppcheck this way: cppcheck --inline-suppr test.c you can specify that the inline suppression only applies to a specific symbol: // cppcheck-suppress arrayIndexOutOfBounds symbolName=arr You can write comments for the suppress, however is recommended to use ; or // to specify where they start: // cppcheck-suppress arrayIndexOutOfBounds ; some comment // cppcheck-suppress arrayIndexOutOfBounds // some comment 15 Chapter 10. Library configuration 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. 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. Using your own custom .cfg file 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. It is recommended that you use the Library Editor in the Cppcheck GUI to edit configuration files. It is available in the View menu. All settings are not documented in this manual. If you have a question about the .cfg file format it is recommended you ask in the forum (http://sourceforge.net/p/cppcheck/discussion/). The command line cppcheck will try to load custom .cfg files from the working path - execute cppcheck from the path where the .cfg files are. The cppcheck GUI will try to load custom .cfg files from the project file path. The custom .cfg files should be shown in the Edit Project File dialog that you open from the File menu. Memory/resource leaks Cppcheck has configurable checking for leaks, e.g. you can specify which functions allocate and free memory or resources and which functions do not affect the allocation at all. alloc and dealloc Here is an example program: void test() { HPEN pen = CreatePen(PS_SOLID, 1, RGB(255,0,0)); } The code example above has a resource leak - CreatePen() is a WinAPI function that creates a pen. However, Cppcheck doesn't assume that return values from functions must be freed. There is no error message: # cppcheck pen1.c Checking pen1.c... If you provide a configuration file then Cppcheck detects the bug: # cppcheck --library=windows.cfg pen1.c Checking pen1.c... [pen1.c:3]: (error) Resource leak: pen 16 Library configuration Here is a minimal windows.cfg file: uninitvar src/file1.c 14 Suppressions10 var The allocation and deallocation functions are organized in groups. Each group is defined in a CreatePen DeleteObject or tag and is identified by its functions. This means, groups with overlapping tags are merged. leak-ignore and use Often the allocated pointer is passed to functions. Example: void test() { char *p = malloc(100); dostuff(p); } If Cppcheck doesn't know what dostuff does, without configuration it will assume that dostuff takes care of the memory so there is no memory leak. To specify that dostuff doesn't take care of the memory in any way, use leak-ignore in the tag (see next section): If instead dostuff takes care of the memory then this can be configured with: The free
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf Linearized : No Page Count : 36 Profile CMM Type : Little CMS Profile Version : 2.3.0 Profile Class : Display Device Profile Color Space Data : RGB Profile Connection Space : XYZ Profile Date Time : 2004:08:13 12:18:06 Profile File Signature : acsp Primary Platform : Apple Computer Inc. CMM Flags : Not Embedded, Independent Device Manufacturer : Little CMS Device Model : Device Attributes : Reflective, Glossy, Positive, Color Rendering Intent : Perceptual Connection Space Illuminant : 0.9642 1 0.82491 Profile Creator : Little CMS Profile ID : 0 Device Mfg Desc : lcms generated Profile Description : sRGB Device Model Desc : sRGB Media White Point : 0.95015 1 1.08826 Red Matrix Column : 0.43585 0.22238 0.01392 Blue Matrix Column : 0.14302 0.06059 0.71384 Green Matrix Column : 0.38533 0.71704 0.09714 Red Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Green Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Blue Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Chromaticity Channels : 3 Chromaticity Colorant : Unknown (0) Chromaticity Channel 1 : 0.64 0.33 Chromaticity Channel 2 : 0.3 0.60001 Chromaticity Channel 3 : 0.14999 0.06 Profile Copyright : no copyright, use freely Format : application/pdf Language : en Date : 2018:10:14 15:09:36+02:00 Producer : Apache FOP Version 2.1 PDF Version : 1.4 Creator Tool : Apache FOP Version 2.1 Metadata Date : 2018:10:14 15:09:36+02:00 Create Date : 2018:10:14 15:09:36+02:00 Creator : Apache FOP Version 2.1EXIF Metadata provided by EXIF.tools