Main Page

From cppcheck

(Difference between revisions)
Jump to: navigation, search
(improved the 'Documents and Articles')
(1.58 is planned to be released on january 12th)
(40 intermediate revisions not shown)
Line 28: Line 28:
'''Manual'''<br>
'''Manual'''<br>
-
The Cppcheck manual is available here: http://cppcheck.sf.net/manual.pdf
+
The Cppcheck manual is available as [http://cppcheck.sourceforge.net/manual.html HTML] and [http://cppcheck.sf.net/manual.pdf PDF].
'''Writing rules'''<br>
'''Writing rules'''<br>
-
In the next Cppcheck version it will be possible for users to define custom rules. The rules will be defined with regular expressions.<br>
+
Articles about writing rules.<br>
[http://sourceforge.net/projects/cppcheck/files/Articles/writing-rules-1.pdf/download Part 1 - Getting started]<br>
[http://sourceforge.net/projects/cppcheck/files/Articles/writing-rules-1.pdf/download Part 1 - Getting started]<br>
[http://sourceforge.net/projects/cppcheck/files/Articles/writing-rules-2.pdf/download Part 2 - Data representation]<br>
[http://sourceforge.net/projects/cppcheck/files/Articles/writing-rules-2.pdf/download Part 2 - Data representation]<br>
-
More articles are coming
+
[http://sourceforge.net/projects/cppcheck/files/Articles/writing-rules-3.pdf/download Part 3 - Introduction to C++ rules]<br>
'''Cppcheck design'''<br>
'''Cppcheck design'''<br>
Line 42: Line 42:
To download the standalone Cppcheck tool: http://www.sourceforge.net/projects/cppcheck
To download the standalone Cppcheck tool: http://www.sourceforge.net/projects/cppcheck
-
Plugins:
+
Clients and plugins (open source):
-
* Code::Blocks
+
* '''Code::Blocks''' - Integrated
-
* Codelite - Integrated
+
* '''Codelite''' - Integrated
-
* Eclipse - http://cppcheclipse.googlecode.com/
+
* '''Eclipse''' - http://cppcheclipse.googlecode.com/
-
* Hudson - http://wiki.hudson-ci.org/display/HUDSON/Cppcheck+Plugin
+
* '''gedit''' - http://github.com/odamite/gedit-cppcheck
 +
* '''Hudson''' - http://wiki.hudson-ci.org/display/HUDSON/Cppcheck+Plugin
 +
* '''Jenkins''' - http://wiki.jenkins-ci.org/display/JENKINS/Cppcheck+Plugin
 +
* '''Tortoise SVN''' - [[tortoisesvn|Adding a pre-commit hook script]]
-
Commercial software:
+
Clients and plugins (commercial)
-
* [http://www.riverblade.co.uk/products/lintproject/index.html LintProject by RiverBlade] - Code analysis with HTML reporting
+
* '''Visual Studio''' / '''Eclipse''' - [http://www.riverblade.co.uk/products/visual_lint/index.html Visual Lint by RiverBlade]
 +
* Command line - [http://www.riverblade.co.uk/products/lintproject/index.html LintProject by RiverBlade]
==Checks==
==Checks==
 +
 +
===64-bit portability===
 +
Check if there is 64-bit portability issues:
 +
* assign address to/from int/long
 +
* casting address from/to integer when returning from function
===Auto Variables===
===Auto Variables===
Line 59: Line 68:
* assigning address of an variable to an effective parameter of a function
* assigning address of an variable to an effective parameter of a function
* returning reference to local/temporary variable
* returning reference to local/temporary variable
 +
* returning address of function parameter
 +
 +
===Boost usage===
 +
Check for invalid usage of Boost:
 +
* container modification during BOOST_FOREACH
===Bounds checking===
===Bounds checking===
Line 65: Line 79:
===Class===
===Class===
Check the code for each class.
Check the code for each class.
-
* Missing constructors
+
* Missing constructors and copy constructors
* Are all variables initialized by the constructors?
* Are all variables initialized by the constructors?
-
* [[CheckMemset|Warn if memset, memcpy etc are used on a class]]
+
* Are all variables assigned by 'operator='?
-
* Are there unused private functions
+
* Warn if memset, memcpy etc are used on a class
 +
* If it's a base class, check that the destructor is virtual
 +
* Are there unused private functions?
* 'operator=' should return reference to self
* 'operator=' should return reference to self
* 'operator=' should check for assignment to self
* 'operator=' should check for assignment to self
* Constness for member functions
* Constness for member functions
 +
* Order of initializations
 +
* Suggest usage of initialization list
 +
* Suspicious subtraction from 'this'
===Exception Safety===
===Exception Safety===
Line 77: Line 96:
* Throwing exceptions in destructors
* Throwing exceptions in destructors
* Throwing exception during invalid state
* Throwing exception during invalid state
 +
* Throwing a copy of a caught exception instead of rethrowing the original exception
 +
* Exception caught by value instead of by reference
-
===Memory leaks (function variables)===
+
===IO===
-
Is there any allocated memory when a function goes out of scope
+
Check input/output operations.
 +
* Bad usage of the function 'sprintf' (overlapping data)
 +
* Missing or wrong width specifiers in 'scanf' format string
 +
* Use a file that has been closed
 +
* File input/output without positioning results in undefined behaviour
 +
* Read to a file that has only been opened for writing (or vice versa)
 +
* Using fflush() on an input stream
 +
* Invalid usage of output stream. For example: 'std::cout << std::cout;'
 +
* Wrong number of arguments given to 'printf' or 'scanf;'
 +
 
 +
===Leaks (auto variables)===
 +
Detect when a auto variable is allocated but not deallocated.
 +
 
 +
===Match assignments and conditions===
 +
Match assignments and conditions:
 +
* Mismatching assignment and comparison => comparison is always true/false
 +
* Mismatching lhs and rhs in comparison => comparison is always true/false
 +
* Detect matching 'if' and 'else if' conditions
 +
 
 +
===Memory leaks (address not taken)===
 +
Not taking the address to allocated memory
===Memory leaks (class variables)===
===Memory leaks (class variables)===
If the constructor allocate memory then the destructor must deallocate it.
If the constructor allocate memory then the destructor must deallocate it.
 +
 +
===Memory leaks (function variables)===
 +
Is there any allocated memory when a function goes out of scope
===Memory leaks (struct members)===
===Memory leaks (struct members)===
Don't forget to deallocate struct members
Don't forget to deallocate struct members
-
===Memory leaks (address not taken)===
+
===Non reentrant functions===
-
Not taking the address to allocated memory
+
Warn if any of these non reentrant functions are used:
 +
* crypt
 +
* ctermid
 +
* ecvt
 +
* fcvt
 +
* fgetgrent
 +
* fgetpwent
 +
* fgetspent
 +
* gcvt
 +
* getgrent
 +
* getgrgid
 +
* getgrnam
 +
* gethostbyaddr
 +
* gethostbyname
 +
* gethostbyname2
 +
* gethostent
 +
* getlogin
 +
* getnetbyaddr
 +
* getnetbyname
 +
* getnetgrent
 +
* getprotobyname
 +
* getpwent
 +
* getpwnam
 +
* getpwuid
 +
* getrpcbyname
 +
* getrpcbynumber
 +
* getrpcent
 +
* getservbyname
 +
* getservbyport
 +
* getservent
 +
* getspent
 +
* getspnam
 +
* gmtime
 +
* localtime
 +
* readdir
 +
* strtok
 +
* tempnam
 +
* ttyname
===Null pointer===
===Null pointer===
Line 96: Line 177:
===Obsolete functions===
===Obsolete functions===
Warn if any of these obsolete functions are used:
Warn if any of these obsolete functions are used:
-
* bsd_signal
+
* asctime_r
-
* gethostbyaddr
+
-
* gethostbyname
+
-
* usleep
+
* bcmp
* bcmp
* bcopy
* bcopy
 +
* bsd_signal
* bzero
* bzero
 +
* ctime_r
* ecvt
* ecvt
* fcvt
* fcvt
 +
* ftime
* gcvt
* gcvt
-
* ftime
 
* getcontext
* getcontext
-
* makecontext
+
* gethostbyaddr
-
* swapcontext
+
* gethostbyname
* getwd
* getwd
* index
* index
-
* rindex
+
* makecontext
* pthread_attr_getstackaddr
* pthread_attr_getstackaddr
* pthread_attr_setstackaddr
* pthread_attr_setstackaddr
 +
* rand_r
 +
* rindex
* scalbln
* scalbln
 +
* swapcontext
 +
* tmpnam
 +
* tmpnam_r
* ualarm
* ualarm
 +
* usleep
 +
* utime
* vfork
* vfork
* wcswcs
* wcswcs
-
* gets
 
===Other===
===Other===
Other checks
Other checks
-
* [[OverlappingData|bad usage of the function 'sprintf' (overlapping data)]]
+
* Assigning bool value to pointer (converting bool value to address)
* division with zero
* division with zero
-
* using fflush() on an input stream
 
* scoped object destroyed immediately after construction
* scoped object destroyed immediately after construction
* assignment in an assert statement
* assignment in an assert statement
 +
* sizeof for array given as function argument
 +
* sizeof for numeric given as function argument
 +
* using sizeof(pointer) instead of the size of pointed data
 +
* incorrect length arguments for 'substr' and 'strncmp'
 +
* free() or delete of an invalid memory location
 +
* double free() or double closedir()
 +
* bitwise operation with negative right operand
 +
* redundant data copying for const variable
 +
* subsequent assignment or copying to a variable or buffer
 +
* Find dead code which is unaccessible due to the counter-conditions check in nested if statements
* C-style pointer cast in cpp file
* C-style pointer cast in cpp file
 +
* casting between incompatible pointer types
* redundant if
* redundant if
* bad usage of the function 'strtol'
* bad usage of the function 'strtol'
* [[CheckUnsignedDivision|unsigned division]]
* [[CheckUnsignedDivision|unsigned division]]
-
* Dangerous usage of 'scanf'
 
-
* unused struct member
 
* passing parameter by value
* passing parameter by value
* [[IncompleteStatement|Incomplete statement]]
* [[IncompleteStatement|Incomplete statement]]
Line 141: Line 235:
* unusal pointer arithmetic. For example: "abc" + 'd'
* unusal pointer arithmetic. For example: "abc" + 'd'
* redundant assignment in a switch statement
* redundant assignment in a switch statement
 +
* redundant pre/post operation in a switch statement
 +
* redundant bitwise operation in a switch statement
 +
* redundant strcpy in a switch statement
* look for 'sizeof sizeof ..'
* look for 'sizeof sizeof ..'
* look for calculations inside sizeof()
* look for calculations inside sizeof()
* assignment of a variable to itself
* assignment of a variable to itself
* mutual exclusion over || always evaluating to true
* mutual exclusion over || always evaluating to true
-
* optimisation: detect post increment/decrement
+
* Clarify calculation with parentheses
-
 
+
* using increment on boolean
-
===Using postfix operators===
+
* comparison of a boolean with a non-zero integer
-
Warn if using postfix operators ++ or -- rather than prefix operator
+
* comparison of a boolean expression with an integer other than 0 or 1
 +
* comparison of a function returning boolean value using relational operator
 +
* comparison of a boolean value with boolean value using relational operator
 +
* suspicious condition (assignment+comparison)
 +
* suspicious condition (runtime comparison of string literals)
 +
* suspicious condition (string literals as boolean)
 +
* suspicious comparison of a string literal with a char* variable
 +
* duplicate break statement
 +
* unreachable code
 +
* testing if unsigned variable is negative
 +
* testing is unsigned variable is positive
 +
* using bool in bitwise expression
 +
* Suspicious use of ; at the end of 'if/for/while' statement.
 +
* incorrect usage of functions from ctype library.
 +
* Comparisons of modulo results that are always true/false.
 +
* Array filled incompletely using memset/memcpy/memmove.
===STL usage===
===STL usage===
Line 161: Line 273:
* redundant condition
* redundant condition
* common mistakes when using string::c_str()
* common mistakes when using string::c_str()
 +
* using auto pointer (auto_ptr)
 +
* useless calls of string and STL functions
===Uninitialized variables===
===Uninitialized variables===
Line 168: Line 282:
===Unused functions===
===Unused functions===
Check for functions that are never called
Check for functions that are never called
 +
 +
===UnusedVar===
 +
UnusedVar checks
 +
* unused variable
 +
* allocated but unused variable
 +
* unred variable
 +
* unassigned variable
 +
* unused struct member
 +
 +
===Using postfix operators===
 +
Warn if using postfix operators ++ or -- rather than prefix operator
==Forum, chat==
==Forum, chat==
Line 175: Line 300:
server: [irc://irc.freenode.net irc.freenode.net]
server: [irc://irc.freenode.net irc.freenode.net]
-
Forum: http://apps.sourceforge.net/phpbb/cppcheck///
+
Forum: http://apps.sourceforge.net/phpbb/cppcheck/
==Future releases==
==Future releases==
The plan is to release a new version every 1-2 months.<br>
The plan is to release a new version every 1-2 months.<br>
-
Version 1.47 is planned to be released on February 5th
+
Version 1.58 is planned to be released on Janary 12th.
==Bugs and feature requests==
==Bugs and feature requests==
Line 205: Line 330:
==Getting the source code==
==Getting the source code==
-
Latest version can be found in the [http://github.com/danmar/cppcheck/ cppcheck git repository]. To download it, run the following command:
+
Latest version can be found in the [http://github.com/danmar/cppcheck/ cppcheck git repository].
 +
 
 +
To get the source code using git:
  git clone git://github.com/danmar/cppcheck.git
  git clone git://github.com/danmar/cppcheck.git
 +
 +
To get the source code using subversion:
 +
 +
svn checkout https://github.com/danmar/cppcheck/trunk
You can also [http://github.com/danmar/cppcheck/downloads download the latest sources in a zip or tgz archive] from the github website.
You can also [http://github.com/danmar/cppcheck/downloads download the latest sources in a zip or tgz archive] from the github website.
Line 214: Line 345:
[[Found_bugs|Found bugs]]
[[Found_bugs|Found bugs]]
 +
 +
==Scanned projects==
 +
To test Cppcheck we scan various projects.
 +
 +
Some of projects are:
 +
 +
[[ScanLinuxKernel|Linux Kernel 3.0.1]]
 +
 +
[[ScanJuliet|SAMATE Juliet Test Suite]] (working in progress)

Revision as of 13:45, 4 November 2012

Contents

Cppcheck - A tool for static C/C++ code analysis

Overview

Cppcheck is an analysis tool for C/C++ code. Unlike C/C++ compilers and many other analysis tools, we don't detect syntax errors. Cppcheck only detects the types of bugs that the compilers normally fail to detect. The goal is no false positives.

We recommend that you enable as many warnings as possible in your compiler.
If you use Visual C++: you should use warning level 4.
If you use GCC: take a look at Warning options - using GCC
If you use another compiler: look in the manual.

Supported platforms:

  • You can check non-standard code that includes various compiler extensions, inline assembly code, etc.
  • Cppcheck is supposed to be compilable by any C++ compiler which handles the latest C++ standard.
  • Cppcheck is supposed to work on any platform that has sufficient cpu and memory.

Accuracy

Cppcheck is far from finished, it is continuosly improved to make it more accurate.

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 (with for example valgrind), than by using Cppcheck.
It is unlikely that you will find all the bugs in your software through testing and instrumenting. Cppcheck can detect some of the bugs that you have missed.

Documents and articles

Manual
The Cppcheck manual is available as HTML and PDF.

Writing rules
Articles about writing rules.
Part 1 - Getting started
Part 2 - Data representation
Part 3 - Introduction to C++ rules

Cppcheck design
False warnings are not inevitable for static analysis tools. This article shows how Cppcheck tries to avoid false warnings.

Clients and plugins

To download the standalone Cppcheck tool: http://www.sourceforge.net/projects/cppcheck

Clients and plugins (open source):

Clients and plugins (commercial)

Checks

64-bit portability

Check if there is 64-bit portability issues:

  • assign address to/from int/long
  • casting address from/to integer when returning from function

Auto Variables

A pointer to a variable is only valid as long as the variable is in scope. Check:

  • returning a pointer to auto or temporary variable
  • assigning address of an variable to an effective parameter of a function
  • returning reference to local/temporary variable
  • returning address of function parameter

Boost usage

Check for invalid usage of Boost:

  • container modification during BOOST_FOREACH

Bounds checking

out of bounds checking

Class

Check the code for each class.

  • Missing constructors and copy constructors
  • Are all variables initialized by the constructors?
  • Are all variables assigned by 'operator='?
  • Warn if memset, memcpy etc are used on a class
  • If it's a base class, check that the destructor is virtual
  • Are there unused private functions?
  • 'operator=' should return reference to self
  • 'operator=' should check for assignment to self
  • Constness for member functions
  • Order of initializations
  • Suggest usage of initialization list
  • Suspicious subtraction from 'this'

Exception Safety

Checking exception safety

  • Throwing exceptions in destructors
  • Throwing exception during invalid state
  • Throwing a copy of a caught exception instead of rethrowing the original exception
  • Exception caught by value instead of by reference

IO

Check input/output operations.

  • Bad usage of the function 'sprintf' (overlapping data)
  • Missing or wrong width specifiers in 'scanf' format string
  • Use a file that has been closed
  • File input/output without positioning results in undefined behaviour
  • Read to a file that has only been opened for writing (or vice versa)
  • Using fflush() on an input stream
  • Invalid usage of output stream. For example: 'std::cout << std::cout;'
  • Wrong number of arguments given to 'printf' or 'scanf;'

Leaks (auto variables)

Detect when a auto variable is allocated but not deallocated.

Match assignments and conditions

Match assignments and conditions:

  • Mismatching assignment and comparison => comparison is always true/false
  • Mismatching lhs and rhs in comparison => comparison is always true/false
  • Detect matching 'if' and 'else if' conditions

Memory leaks (address not taken)

Not taking the address to allocated memory

Memory leaks (class variables)

If the constructor allocate memory then the destructor must deallocate it.

Memory leaks (function variables)

Is there any allocated memory when a function goes out of scope

Memory leaks (struct members)

Don't forget to deallocate struct members

Non reentrant functions

Warn if any of these non reentrant functions are used:

  • crypt
  • ctermid
  • ecvt
  • fcvt
  • fgetgrent
  • fgetpwent
  • fgetspent
  • gcvt
  • getgrent
  • getgrgid
  • getgrnam
  • gethostbyaddr
  • gethostbyname
  • gethostbyname2
  • gethostent
  • getlogin
  • getnetbyaddr
  • getnetbyname
  • getnetgrent
  • getprotobyname
  • getpwent
  • getpwnam
  • getpwuid
  • getrpcbyname
  • getrpcbynumber
  • getrpcent
  • getservbyname
  • getservbyport
  • getservent
  • getspent
  • getspnam
  • gmtime
  • localtime
  • readdir
  • strtok
  • tempnam
  • ttyname

Null pointer

Null pointers

  • null pointer dereferencing

Obsolete functions

Warn if any of these obsolete functions are used:

  • asctime_r
  • bcmp
  • bcopy
  • bsd_signal
  • bzero
  • ctime_r
  • ecvt
  • fcvt
  • ftime
  • gcvt
  • getcontext
  • gethostbyaddr
  • gethostbyname
  • getwd
  • index
  • makecontext
  • pthread_attr_getstackaddr
  • pthread_attr_setstackaddr
  • rand_r
  • rindex
  • scalbln
  • swapcontext
  • tmpnam
  • tmpnam_r
  • ualarm
  • usleep
  • utime
  • vfork
  • wcswcs

Other

Other checks

  • Assigning bool value to pointer (converting bool value to address)
  • division with zero
  • scoped object destroyed immediately after construction
  • assignment in an assert statement
  • sizeof for array given as function argument
  • sizeof for numeric given as function argument
  • using sizeof(pointer) instead of the size of pointed data
  • incorrect length arguments for 'substr' and 'strncmp'
  • free() or delete of an invalid memory location
  • double free() or double closedir()
  • bitwise operation with negative right operand
  • redundant data copying for const variable
  • subsequent assignment or copying to a variable or buffer
  • Find dead code which is unaccessible due to the counter-conditions check in nested if statements
  • C-style pointer cast in cpp file
  • casting between incompatible pointer types
  • redundant if
  • bad usage of the function 'strtol'
  • unsigned division
  • passing parameter by value
  • Incomplete statement
  • check how signed char variables are used
  • variable scope can be limited
  • condition that is always true/false
  • unusal pointer arithmetic. For example: "abc" + 'd'
  • redundant assignment in a switch statement
  • redundant pre/post operation in a switch statement
  • redundant bitwise operation in a switch statement
  • redundant strcpy in a switch statement
  • look for 'sizeof sizeof ..'
  • look for calculations inside sizeof()
  • assignment of a variable to itself
  • mutual exclusion over || always evaluating to true
  • Clarify calculation with parentheses
  • using increment on boolean
  • comparison of a boolean with a non-zero integer
  • comparison of a boolean expression with an integer other than 0 or 1
  • comparison of a function returning boolean value using relational operator
  • comparison of a boolean value with boolean value using relational operator
  • suspicious condition (assignment+comparison)
  • suspicious condition (runtime comparison of string literals)
  • suspicious condition (string literals as boolean)
  • suspicious comparison of a string literal with a char* variable
  • duplicate break statement
  • unreachable code
  • testing if unsigned variable is negative
  • testing is unsigned variable is positive
  • using bool in bitwise expression
  • Suspicious use of ; at the end of 'if/for/while' statement.
  • incorrect usage of functions from ctype library.
  • Comparisons of modulo results that are always true/false.
  • Array filled incompletely using memset/memcpy/memmove.

STL usage

Check for invalid usage of STL:

  • out of bounds errors
  • misuse of iterators when iterating through a container
  • mismatching containers in calls
  • dereferencing an erased iterator
  • for vectors: using iterator/pointer after push_back has been used
  • optimisation: use empty() instead of size() to guarantee fast code
  • suspicious condition when using find
  • redundant condition
  • common mistakes when using string::c_str()
  • using auto pointer (auto_ptr)
  • useless calls of string and STL functions

Uninitialized variables

Uninitialized variables

  • using uninitialized variables and data

Unused functions

Check for functions that are never called

UnusedVar

UnusedVar checks

  • unused variable
  • allocated but unused variable
  • unred variable
  • unassigned variable
  • unused struct member

Using postfix operators

Warn if using postfix operators ++ or -- rather than prefix operator

Forum, chat

IRC channel:
channel: #cppcheck
server: irc.freenode.net

Forum: http://apps.sourceforge.net/phpbb/cppcheck/

Future releases

The plan is to release a new version every 1-2 months.

Version 1.58 is planned to be released on Janary 12th.

Bugs and feature requests

Use Trac to report any problems: http://apps.sourceforge.net/trac/cppcheck/

Defects are for severe bugs such as:

  • False positives
  • Cppcheck hangs/crashes
  • Fail to compile

Enhancements are for issues such as:

  • Fail to detect bug
  • Change the output of Cppcheck
  • Suggestion for a new check

Contribute

You are welcome to contribute. Help is needed.

  • Testing - Pick a project and test it's source with latest version. Write tickets to Trac about issues you find from Cppcheck. If you test open source projects and write bug reports to them, check the issues in Found bugs section, and write links to the bug reports you have created e.g. to our forum, so we can keep a track about them.
  • Developing - Pick a ticket from Trac, write a test case for it (and write a comment to the ticket that test case has been created). Or pick a test case that fails and try to fix it. Make a patch and submit it to Trac either inline if it is small, or attach it as a file.
  • Marketing - Write articles, reviews or tell your friends about us. The more users we have, the more people we have testing and the better we can become.
  • Design - Invent new good checks and create tickets to Trac about them.
  • Integration - Write a plugin to your favorite IDE or create a package for your distribution or operating system.
  • Technical Writer - Write better documentation for the bugs we find. Currently only a few bugs have any documentation at all.

Getting the source code

Latest version can be found in the cppcheck git repository.

To get the source code using git:

git clone git://github.com/danmar/cppcheck.git

To get the source code using subversion:

svn checkout https://github.com/danmar/cppcheck/trunk

You can also download the latest sources in a zip or tgz archive from the github website.

Found bugs

Found bugs

Scanned projects

To test Cppcheck we scan various projects.

Some of projects are:

Linux Kernel 3.0.1

SAMATE Juliet Test Suite (working in progress)

Personal tools