Other features

Important

This documentation is not recommended for new RISC-V projects. New RISC-V projects should reference the newest version of the documentation. Users targeting Arm devices can still use this documentation as their reference.

The newest version of the documentation can be found here: https://mi-v-ecosystem.github.io/SoftConsole-Documentation/

Crypto Application Library

The Crypto Application Library (CAL) provides the software API to access User Crypto block on the PolarFire and PolarFire SoC device families.

If license was agreed on installation, then the library is installed in <SC_INSTALL_DIR>/extras/CAL/ path and contains these following folders/files:

  • cal-src crypto sources in an as-is form, user can use these for reference, but they are not a SoftConsole project

  • mpfs-user-crypto-lib a SoftConsole project which after compilation will produce the following files:

    • mpfs-rv64g-user-crypto-lib.a (U54)

    • mpfs-rv64imac-user-crypto-lib.a (E51)

    These files can be used with PolarFire SoC crypto examples located on the GitHub

  • miv-rv32-user-crypto-lib a SoftConsole project which after compilation will produce the following files:

    • miv-rv32imc-user-crypto-lib.a

    • miv-rv32i-user-crypto-lib.a

    These files can be used with Mi-V Soft processor crypto examples located on the GitHub

  • user_guide.pdf Documentation for the CAL API

Note

The crypto-lib projects can be imported as any other generic/regular SoftConsole projects. Users who know how to import projects can skip the rest of the section.

To import in into the workspace do the following:

digraph {
         graph [rankdir="LR", ranksep=.01, bgcolor=transparent];
         node [fontname="Verdana", fontsize="9", shape="rectangle", width=.1, height=.2, margin=".04,.01", style=filled, fillcolor=white];
         edge [arrowsize=.7];
         "SoftConsole Menu toolbar" -> "File" -> "Import" -> "Existing Projects into Workspace"
     }

After Import dialog is showed do following:

digraph {
         graph [rankdir="LR", ranksep=.01, bgcolor=transparent];
         node [fontname="Verdana", fontsize="9", shape="rectangle", width=.1, height=.2, margin=".04,.01", style=filled, fillcolor=white];
         edge [arrowsize=.7];
         "Select root directory" -> "Browse..." -> "find and select the 'miv-rv32-user-crypto-lib' folder" -> "Open"
     }

If the dialog was left in the default state (as provided from a fresh workspace) and the project was not imported already into the workspace, then clicking the Finish button will import it correctly into the workspace.

Built-in serial terminal view

SoftConsole includes a built-in serial terminal view which obviates the need to run a separate serial terminal emulator when connecting to a target board using a UART. The plug-ins used to implement this view are preinstalled. Refer to this blog post for information on how to show and configure the terminal view (but skip the parts dealing with plug-in installation as this is already done):

https://mcuoneclipse.com/2017/10/07/using-serial-terminal-and-com-support-in-eclipse-oxygen-and-neon/

In order for the serial terminal to list the relevant serial/COM ports, especially for USB serial ports, the relevant OS drivers may need to be installed. Refer to the relevant hardware/board documentation for more details.

Integer only newlib support

SoftConsole bundles newlib standard library support (https://sourceware.org/newlib/).

It is often possible to build embedded programs in constrained resource (CPU, memory etc.) environments without linking in any standard library overhead. However, where standard library support must be used newlib offers a couple of ways to reduce the overhead:

  • Smaller integer only *iprintf() APIs (e.g. iprintf(), siprintf(), fiprintf() etc.) that avoid the significant additional overhead of floating point support. Refer to the newlib documentation for more information.

  • Nano newlib which is a cut down version of the standard newlib library. To use newlib-nano go to the linker settings of your project properties:

    digraph { graph [rankdir="LR", ranksep=.01, bgcolor=transparent]; node [fontname="Verdana", style=filled, fillcolor=white, fontsize="9", shape="rectangle", width=.1, height=.2, margin=".04,.01"]; edge [arrowsize=.7]; "Project Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "Cross Arm GNU C/C++ Linker"; }

    and check the Use newlib-nano option:

    digraph { graph [rankdir="LR", ranksep=.01, bgcolor=transparent]; node [fontname="Verdana", style=filled, fillcolor=white, fontsize="9", shape="rectangle", width=.1, height=.2, margin=".04,.01"]; edge [arrowsize=.7]; "Cross Arm GNU C/C++ Linker" -> "Miscellaneous" -> "Use newlib-nano (--specs=nano.specs)" ; }

Static stack profiling

GCC supports static stack usage analysis/profiling. Depending on the nature of the application these might not be as predictable and might require an engineer to evaluate the application manually and manually decide on the sizes. See here for more on this and add the relevant options to the project settings as required:

https://mcuoneclipse.com/2015/08/21/gnu-static-stack-usage-analysis/

https://dzone.com/articles/gnu-static-stack-usage-analysis

https://gcc.gnu.org/onlinedocs/gnat_ugn/Static-Stack-Usage-Analysis.html

https://stackoverflow.com/questions/6387614

https://www.adacore.com/uploads/technical-papers/Stack_Analysis.pdf

The -fstack-usage can show what parts consume how much stuck, when run on mpfs-mustein-julia example it can show in the file fractal_display.su (the static usage has .su extension) that one function is allocating a non-negledable amount on the stack (64KiB):

1
2
3
fractal_display.c:70:6:transition 160 static
fractal_display.c:84:6:fractalLoop 80 static
fractal_display.c:115:6:juliaMain 65568 static

Opening the fractal_display.c will show that there is a buffer allocated (pixel buffer 128 pixels by 128 pixels big, with 4 bytes per pixel):

1
2
3
void juliaMain(uint64_t base)
{
uint32_t buffer[SCREEN_WIDTH * SCREEN_HEIGHT];

This either has to be refactored and removed from the stack or it needs to be considered inside the linker script stack allocation. Moving some buffers from local (stack) to the global scope (bss/data) will make their size predictable as there will be guaranteed only one instance present. While keeping them locally might cause multiple allocations if the function is invoked recursively. Sometimes this is necessary and each nested invocation needs their own instance of the variable and sometimes moving variables to globals can be considered as a code smell, therefore blindly moving local variables to global scope might create more problems and bugs. Consider all the pros and cons of each section of code and make decisions case by case.

The size of variables has an impact, but their nesting as well, recursive algorithms might take a significant amount of iterations and allocations on the stack (even if they are using small variables). Many application and algorithms by their nature cannot by predicted statically with 100% confidence and depend significantly on their run-time behavior. Therefore the analysis tools should be considered as guiding helpers which can show a problematic place in code but can’t be blindly trusted.

Other tools such as LDRA, cppcheck (but not limited to) could be used to analyses the code and spot some potential issues. Sometimes when stack size can’t be increased it might be possible to refactor the code and conserve the stack allocations as much as possible.

If the C or C++ application is allocating variables dynamically, then heap size should be evaluated as well:

https://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

See:

Renode simulation platform

Deeply nested code causes crashes and glitches

Cppcheck

Cppcheck is a C/C++ source code static analysis tool and cppcheclipse is an Eclipse plugin that integrates cppcheck into the Eclipse/CDT SoftConsole IDE. Using cppcheck/cppcheclipse projects can be scanned for common source code issues and bugs each time the project is built or on demand. The configuration options for cppcheck/cppcheclipse are accessible via:

digraph {
         graph [rankdir="LR", ranksep=.01, bgcolor=transparent];
         node [fontname="Verdana", fontsize="9", shape="rectangle", width=.1, height=.2, margin=".04,.01", style=filled, fillcolor=white];
         edge [arrowsize=.7];
         "Project Properties" -> "cppchecklipse"
     }

For more information on using cppcheck/cppcheclipse source code static analysis capabilities refer to these links:

cppcheck can also be used from command line or as part of a Makefile based project. The required cppcheck binaries are located in <SoftConsole-install-dir>/extras/cppcheck.

Cppcheck was not intended to replace all analysis tools so it is recommended to use other analysis tools (not bundled with SoftConsole) as well.

Suppressing issues

If there is genuine good need to suppress a specific issue on a single line, then the following code can be copied to the code. Cppcheck will recognize the comment in the code and suppress a specific issue on that line.

Resolving the issues instead of suppressing them is preferred, however in edge cases (false positives and bugs in cppcheck) it might be necessary to suppress some issues.

Note

If there is no need to suppress any issues, then feel free to ignore this section.

Error

autoVariables
// cppcheck-suppress autoVariables

Message: Address of local auto-variable assigned to a function parameter.

Verbose explanation: Dangerous assignment - the function parameter is assigned the address of a local auto-variable. Local auto-variables are reserved from the stack which is freed when the function ends. So the pointer to a local variable is invalid after the function ends.

Common Weakness Enumeration: 562

returnAddressOfAutoVariable
// cppcheck-suppress returnAddressOfAutoVariable

Message: Address of an auto-variable returned.

Common Weakness Enumeration: 562

returnLocalVariable
// cppcheck-suppress returnLocalVariable

Message: Pointer to local array variable returned.

Common Weakness Enumeration: 562

returnReference
// cppcheck-suppress returnReference

Message: Reference to auto variable returned.

Common Weakness Enumeration: 562

returnTempReference
// cppcheck-suppress returnTempReference

Message: Reference to temporary returned.

Common Weakness Enumeration: 562

autovarInvalidDeallocation
// cppcheck-suppress autovarInvalidDeallocation

Message: Deallocation of an auto-variable results in undefined behaviour.

Verbose explanation: The deallocation of an auto-variable results in undefined behaviour. You should only free memory that has been allocated dynamically.

Common Weakness Enumeration: 590

returnAddressOfFunctionParameter
// cppcheck-suppress returnAddressOfFunctionParameter

Message: Address of function parameter ‘parameter’ returned.

Verbose explanation: Address of the function parameter ‘parameter’ becomes invalid after the function exits because function parameters are stored on the stack which is freed when the function exits. Thus the returned value is invalid.

Common Weakness Enumeration: 56

returnDanglingLifetime
// cppcheck-suppress returnDanglingLifetime

Message: Returning object that will be invalid when returning.

Common Weakness Enumeration: 562

invalidLifetime
// cppcheck-suppress invalidLifetime

Message: Using object that is out of scope.

Common Weakness Enumeration: 562

danglingLifetime
// cppcheck-suppress danglingLifetime

Message: Non-local variable ‘x’ will use object.

Common Weakness Enumeration: 562

assignBoolToPointer
// cppcheck-suppress assignBoolToPointer

Message: Boolean value assigned to pointer.

Common Weakness Enumeration: 587

pointerArithBool
// cppcheck-suppress pointerArithBool

Message: Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.

Verbose explanation: Converting pointer arithmetic result to bool. The boolean result is always true unless there is pointer arithmetic overflow, and overflow is undefined behaviour. Probably a dereference is forgotten.

Common Weakness Enumeration: 571

boostForeachError
// cppcheck-suppress boostForeachError

Message: BOOST_FOREACH caches the end() iterator. It’s undefined behavior if you modify the container inside.

Common Weakness Enumeration: 664

arrayIndexOutOfBounds
// cppcheck-suppress arrayIndexOutOfBounds

Message: Array ‘array[2]’ index array[1][1] out of bounds.

Common Weakness Enumeration: 78

bufferAccessOutOfBounds
// cppcheck-suppress bufferAccessOutOfBounds

Message: Buffer is accessed out of bounds: buffer

Common Weakness Enumeration: 78

outOfBounds
// cppcheck-suppress outOfBounds

Message: index is out of bounds: Supplied size 2 is larger than actual size 1.

Common Weakness Enumeration: 788

negativeIndex
// cppcheck-suppress negativeIndex

Message: Array index -1 is out of bounds.

Common Weakness Enumeration: 786

insecureCmdLineArgs
// cppcheck-suppress insecureCmdLineArgs

Message: Buffer overrun possible for long command line arguments.

Common Weakness Enumeration: 119

negativeMemoryAllocationSize
// cppcheck-suppress negativeMemoryAllocationSize

Message: Memory allocation size is negative.

Verbose explanation: Memory allocation size is negative.Negative allocation size has no specified behaviour.

Common Weakness Enumeration: 131

negativeArraySize
// cppcheck-suppress negativeArraySize

Message: Declaration of array ‘’ with negative size is undefined behaviour

Common Weakness Enumeration: 758

invalidFunctionArg
// cppcheck-suppress invalidFunctionArg

Message: Invalid func_name() argument nr 1. The value is 0 or 1 (boolean) but the valid values are ‘1:4’.

Common Weakness Enumeration: 62

invalidFunctionArgBool
// cppcheck-suppress invalidFunctionArgBool

Message: Invalid func_name() argument nr 1. A non-boolean value is required.

Common Weakness Enumeration: 62

invalidFunctionArgStr
// cppcheck-suppress invalidFunctionArgStr

Message: Invalid func_name() argument nr 1. A nul-terminated string is required.

Common Weakness Enumeration: 62

memsetClass
// cppcheck-suppress memsetClass

Message: Using ‘memfunc’ on class that contains a classname.

Verbose explanation: Using ‘memfunc’ on class that contains a classname is unsafe, because constructor, destructor and copy operator calls are omitted. These are necessary for this non-POD type to ensure that a valid object is created.

Common Weakness Enumeration: 76

memsetClassReference
// cppcheck-suppress memsetClassReference

Message: Using ‘memfunc’ on class that contains a reference.

Common Weakness Enumeration: 66

mallocOnClassError
// cppcheck-suppress mallocOnClassError

Message: Memory for class instance allocated with malloc(), but class contains a std::string.

Verbose explanation: Memory for class instance allocated with malloc(), but class a std::string. This is unsafe, since no constructor is called and class members remain uninitialized. Consider using ‘new’ instead.

Common Weakness Enumeration: 66

virtualDestructor
// cppcheck-suppress virtualDestructor

Message: Class ‘Base’ which is inherited by class ‘Derived’ does not have a virtual destructor.

Verbose explanation: Class ‘Base’ which is inherited by class ‘Derived’ does not have a virtual destructor. If you destroy instances of the derived class by deleting a pointer that points to the base class, only the destructor of the base class is executed. Thus, dynamic memory that is managed by the derived class could leak. This can be avoided by adding a virtual destructor to the base class.

Common Weakness Enumeration: 40

operatorEqMissingReturnStatement
// cppcheck-suppress operatorEqMissingReturnStatement

Message: No ‘return’ statement in non-void function causes undefined behavior.

Common Weakness Enumeration: 398

selfInitialization
// cppcheck-suppress selfInitialization

Message: Member variable ‘var’ is initialized by itself.

Common Weakness Enumeration: 66

throwInNoexceptFunction
// cppcheck-suppress throwInNoexceptFunction

Message: Exception thrown in function declared not to throw exceptions.

Common Weakness Enumeration: 398

coutCerrMisusage
// cppcheck-suppress coutCerrMisusage

Message: Invalid usage of output stream: ‘<< std::cout’.

Common Weakness Enumeration: 398

IOWithoutPositioning
// cppcheck-suppress IOWithoutPositioning

Message: Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.

Common Weakness Enumeration: 664

readWriteOnlyFile
// cppcheck-suppress readWriteOnlyFile

Message: Read operation on a file that was opened only for writing.

Common Weakness Enumeration: 664

writeReadOnlyFile
// cppcheck-suppress writeReadOnlyFile

Message: Write operation on a file that was opened only for reading.

Common Weakness Enumeration: 664

useClosedFile
// cppcheck-suppress useClosedFile

Message: Used file that is not opened.

Common Weakness Enumeration: 910

wrongPrintfScanfArgNum
// cppcheck-suppress wrongPrintfScanfArgNum

Message: printf format string requires 3 parameters but only 2 are given.

Common Weakness Enumeration: 685

invalidScanfFormatWidth
// cppcheck-suppress invalidScanfFormatWidth

Message: Width 5 given in format string (no. 10) is larger than destination buffer ‘[0]’, use %-1s to prevent overflowing it.

Common Weakness Enumeration: 687

deallocret
// cppcheck-suppress deallocret

Message: Returning/dereferencing ‘p’ after it is deallocated / released

Common Weakness Enumeration: 67

doubleFree
// cppcheck-suppress doubleFree

Message: Memory pointed to by ‘varname’ is freed twice.

Common Weakness Enumeration: 41

leakNoVarFunctionCall
// cppcheck-suppress leakNoVarFunctionCall

Message: Allocation with funcName, funcName doesn’t release it.

Common Weakness Enumeration: 772

leakReturnValNotUsed
// cppcheck-suppress leakReturnValNotUsed

Message: Return value of allocation function ‘funcName’ is not stored.

Common Weakness Enumeration: 77

memleak
// cppcheck-suppress memleak

Message: Memory leak: varname

Common Weakness Enumeration: 40

resourceLeak
// cppcheck-suppress resourceLeak

Message: Resource leak: varname

Common Weakness Enumeration: 77

deallocDealloc
// cppcheck-suppress deallocDealloc

Message: Deallocating a deallocated pointer: varname

Common Weakness Enumeration: 41

deallocuse
// cppcheck-suppress deallocuse

Message: Dereferencing ‘varname’ after it is deallocated / released

Common Weakness Enumeration: 41

mismatchSize
// cppcheck-suppress mismatchSize

Message: The allocated size sz is not a multiple of the underlying type’s size.

Common Weakness Enumeration: 131

mismatchAllocDealloc
// cppcheck-suppress mismatchAllocDealloc

Message: Mismatching allocation and deallocation: varname

Common Weakness Enumeration: 76

memleakOnRealloc
// cppcheck-suppress memleakOnRealloc

Message: Common realloc mistake: ‘varname’ nulled but not freed upon failure

Common Weakness Enumeration: 40

nullPointer
// cppcheck-suppress nullPointer

Message: Null pointer dereference

Common Weakness Enumeration: 476

nullPointerArithmetic
// cppcheck-suppress nullPointerArithmetic

Message: Pointer arithmetic with NULL pointer.

Common Weakness Enumeration: 682

zerodiv
// cppcheck-suppress zerodiv

Message: Division by zero.

Common Weakness Enumeration: 369

zerodivcond
// cppcheck-suppress zerodivcond

Message: Either the condition is redundant or there is division by zero.

Common Weakness Enumeration: 369

shiftNegative
// cppcheck-suppress shiftNegative

Message: Shifting by a negative value is undefined behaviour

Common Weakness Enumeration: 758

wrongPipeParameterSize
// cppcheck-suppress wrongPipeParameterSize

Message: Buffer ‘varname’ must have size of 2 integers if used as parameter of pipe().

Verbose explanation: The pipe()/pipe2() system command takes an argument, which is an array of exactly two integers. The variable ‘varname’ is an array of size dimension, which does not match.

Common Weakness Enumeration: 68

raceAfterInterlockedDecrement
// cppcheck-suppress raceAfterInterlockedDecrement

Message: Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.

Common Weakness Enumeration: 362

invalidFree
// cppcheck-suppress invalidFree

Message: Invalid memory address freed.

unknownEvaluationOrder
// cppcheck-suppress unknownEvaluationOrder

Message: Expression ‘x = x++;’ depends on order of evaluation of side effects

Common Weakness Enumeration: 768

containerOutOfBounds
// cppcheck-suppress containerOutOfBounds

Message: Out of bounds access of item in container ‘var’

Common Weakness Enumeration: 39

invalidIterator1
// cppcheck-suppress invalidIterator1

Message: Invalid iterator: iterator

Common Weakness Enumeration: 66

iterators1
// cppcheck-suppress iterators1

Message: Same iterator is used with different containers ‘container1’ and ‘container2’.

Common Weakness Enumeration: 66

iterators3
// cppcheck-suppress iterators3

Message: Same iterator is used with containers ‘container’ that are defined in different scopes.

Common Weakness Enumeration: 66

iteratorsCmp1
// cppcheck-suppress iteratorsCmp1

Message: Comparison of iterators from containers ‘container1’ and ‘container2’.

Common Weakness Enumeration: 66

iteratorsCmp2
// cppcheck-suppress iteratorsCmp2

Message: Comparison of iterators from containers ‘container’ that are defined in different scopes.

Common Weakness Enumeration: 66

mismatchingContainers
// cppcheck-suppress mismatchingContainers

Message: Iterators of different containers are used together.

Common Weakness Enumeration: 664

eraseDereference
// cppcheck-suppress eraseDereference

Message: Invalid iterator ‘iter’ used.

Verbose explanation: The iterator ‘iter’ is invalid before being assigned. Dereferencing or comparing it with another iterator is invalid operation.

Common Weakness Enumeration: 66

stlOutOfBounds
// cppcheck-suppress stlOutOfBounds

Message: When i==foo.size(), foo[i] is out of bounds.

Common Weakness Enumeration: 78

invalidIterator2
// cppcheck-suppress invalidIterator2

Message: After push_back/push_front/insert(), the iterator ‘iterator’ may be invalid.

Common Weakness Enumeration: 66

invalidPointer
// cppcheck-suppress invalidPointer

Message: Invalid pointer ‘pointer’ after push_back().

Common Weakness Enumeration: 66

stlBoundaries
// cppcheck-suppress stlBoundaries

Message: Dangerous comparison using operator< on iterator.

Verbose explanation: Iterator compared with operator<. This is dangerous since the order of items in the container is not guaranteed. One should use operator!= instead to compare iterators.

Common Weakness Enumeration: 664

stlcstr
// cppcheck-suppress stlcstr

Message: Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.

Verbose explanation: Dangerous usage of c_str(). The c_str() return value is only valid until its string is deleted.

Common Weakness Enumeration: 664

stlcstrthrow
// cppcheck-suppress stlcstrthrow

Message: Dangerous usage of c_str(). The value returned by c_str() is invalid after throwing exception.

Verbose explanation: Dangerous usage of c_str(). The string is destroyed after the c_str() call so the thrown pointer is invalid.

useAutoPointerContainer
// cppcheck-suppress useAutoPointerContainer

Message: You can randomly lose access to pointers if you store ‘auto_ptr’ pointers in an STL container.

Verbose explanation: An element of container must be able to be copied but ‘auto_ptr’ does not fulfill this requirement. You should consider to use ‘shared_ptr’ or ‘unique_ptr’. It is suitable for use in containers, because they no longer copy their values, they move them.

Common Weakness Enumeration: 664

useAutoPointerArray
// cppcheck-suppress useAutoPointerArray

Message: Object pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. You should not use ‘auto_ptr’ for pointers obtained with operator ‘new[]’.

Verbose explanation: Object pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. This means that you should only use ‘auto_ptr’ for pointers obtained with operator ‘new’. This excludes arrays, which are allocated by operator ‘new[]’ and must be deallocated by operator ‘delete[]’.

Common Weakness Enumeration: 664

useAutoPointerMalloc
// cppcheck-suppress useAutoPointerMalloc

Message: Object pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. You should not use ‘auto_ptr’ for pointers obtained with function ‘malloc’.

Verbose explanation: Object pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. You should not use ‘auto_ptr’ for pointers obtained with function ‘malloc’. This means that you should only use ‘auto_ptr’ for pointers obtained with operator ‘new’. This excludes use C library allocation functions (for example ‘malloc’), which must be deallocated by the appropriate C library function.

Common Weakness Enumeration: 76

stringLiteralWrite
// cppcheck-suppress stringLiteralWrite

Message: Modifying string literal directly or indirectly is undefined behaviour.

Common Weakness Enumeration: 758

sprintfOverlappingData
// cppcheck-suppress sprintfOverlappingData

Message: Undefined behavior: Variable ‘varname’ is used as parameter and destination in s[n]printf().

Verbose explanation: The variable ‘varname’ is used both as a parameter and as destination in s[n]printf(). The origin and destination buffers overlap. Quote from glibc (C-library) documentation (http://www.gnu.org/software/libc/manual/html_mono/libc.html#Formatted-Output-Functions): “If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined.”

Common Weakness Enumeration: 62

strPlusChar
// cppcheck-suppress strPlusChar

Message: Unusual pointer arithmetic. A value of type ‘char’ is added to a string literal.

Common Weakness Enumeration: 665

shiftTooManyBits
// cppcheck-suppress shiftTooManyBits

Message: Shifting 32-bit value by 40 bits is undefined behaviour

Common Weakness Enumeration: 758

shiftTooManyBitsSigned
// cppcheck-suppress shiftTooManyBitsSigned

Message: Shifting signed 32-bit value by 31 bits is undefined behaviour

Common Weakness Enumeration: 758

integerOverflow
// cppcheck-suppress integerOverflow

Message: Signed integer overflow for expression ‘’.

Common Weakness Enumeration: 190

floatConversionOverflow
// cppcheck-suppress floatConversionOverflow

Message: Undefined behaviour: float (1e+100) to integer conversion overflow.

Common Weakness Enumeration: 190

uninitstring
// cppcheck-suppress uninitstring

Message: Dangerous usage of ‘varname’ (strncpy doesn’t always null-terminate it).

Common Weakness Enumeration: 67

uninitdata
// cppcheck-suppress uninitdata

Message: Memory is allocated but not initialized: varname

Common Weakness Enumeration: 90

uninitvar
// cppcheck-suppress uninitvar

Message: Uninitialized variable: varname

Common Weakness Enumeration: 90

uninitStructMember
// cppcheck-suppress uninitStructMember

Message: Uninitialized struct member: a.b

Common Weakness Enumeration: 90

deadpointer
// cppcheck-suppress deadpointer

Message: Dead pointer usage. Pointer ‘pointer’ is dead if it has been assigned ‘&x’ at line 0.

Common Weakness Enumeration: 82

va_start_referencePassed
// cppcheck-suppress va_start_referencePassed

Message: Using reference ‘arg1’ as parameter for va_start() results in undefined behaviour.

Common Weakness Enumeration: 758

va_end_missing
// cppcheck-suppress va_end_missing

Message: va_list ‘vl’ was opened but not closed by va_end().

Common Weakness Enumeration: 664

va_list_usedBeforeStarted
// cppcheck-suppress va_list_usedBeforeStarted

Message: va_list ‘vl’ used before va_start() was called.

Common Weakness Enumeration: 664

va_start_subsequentCalls
// cppcheck-suppress va_start_subsequentCalls

Message: va_start() or va_copy() called subsequently on ‘vl’ without va_end() in between.

Common Weakness Enumeration: 664

preprocessorErrorDirective
// cppcheck-suppress preprocessorErrorDirective

Message: #error message

Warning

assertWithSideEffect
// cppcheck-suppress assertWithSideEffect

Message: Assert statement calls a function which may have desired side effects: ‘function’.

Verbose explanation: Non-pure function: ‘function’ is called inside assert statement. Assert statements are removed from release builds so the code inside assert statement is not executed. If the code is needed also in release builds, this is a bug.

Common Weakness Enumeration: 39

assignmentInAssert
// cppcheck-suppress assignmentInAssert

Message: Assert statement modifies ‘var’.

Verbose explanation: Variable ‘var’ is modified insert assert statement. Assert statements are removed from release builds so the code inside assert statement is not executed. If the code is needed also in release builds, this is a bug.

Common Weakness Enumeration: 39

autoVariablesAssignGlobalPointer
// cppcheck-suppress autoVariablesAssignGlobalPointer

Message: Address of local array array is assigned to global pointer pointer and not reassigned before array goes out of scope.

Common Weakness Enumeration: 56

uselessAssignmentPtrArg
// cppcheck-suppress uselessAssignmentPtrArg

Message: Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?

Common Weakness Enumeration: 398

compareBoolExpressionWithInt
// cppcheck-suppress compareBoolExpressionWithInt

Message: Comparison of a boolean expression with an integer other than 0 or 1.

Common Weakness Enumeration: 398

comparisonOfBoolWithInvalidComparator
// cppcheck-suppress comparisonOfBoolWithInvalidComparator

Message: Comparison of a boolean value using relational operator (<, >, <= or >=).

Verbose explanation: The result of the expression ‘expression’ is of type ‘bool’. Comparing ‘bool’ value using relational (<, >, <= or >=) operator could cause unexpected results.

strncatUsage
// cppcheck-suppress strncatUsage

Message: Dangerous usage of strncat - 3rd parameter is the maximum number of characters to append.

Verbose explanation: At most, strncat appends the 3rd parameter’s amount of characters and adds a terminating null byte. The safe way to use strncat is to subtract one from the remaining space in the buffer and use it as 3rd parameter.

http://www.cplusplus.com/reference/cstring/strncat/

http://www.opensource.apple.com/source/Libc/Libc-167/gen.subproj/i386.subproj/strncat.c

Common Weakness Enumeration: 119

sizeArgumentAsChar
// cppcheck-suppress sizeArgumentAsChar

Message: The size argument is given as a char constant.

Common Weakness Enumeration: 682

terminateStrncpy
// cppcheck-suppress terminateStrncpy

Message: The buffer ‘buffer’ may not be null-terminated after the call to strncpy().

Verbose explanation: The buffer ‘buffer’ may not be null-terminated after the call to strncpy(). If the source string’s size fits or exceeds the given size, strncpy() does not add a zero at the end of the buffer. This causes bugs later in the code if the code assumes buffer is null-terminated.

Common Weakness Enumeration: 170

bufferNotZeroTerminated
// cppcheck-suppress bufferNotZeroTerminated

Message: The buffer ‘buffer’ is not null-terminated after the call to strncpy().

Verbose explanation: The buffer ‘buffer’ is not null-terminated after the call to strncpy(). This will cause bugs later in the code if the code assumes the buffer is null-terminated.

Common Weakness Enumeration: 170

possibleBufferAccessOutOfBounds
// cppcheck-suppress possibleBufferAccessOutOfBounds

Message: Possible buffer overflow if strlen(source) is larger than or equal to sizeof(destination).

Verbose explanation: Possible buffer overflow if strlen(source) is larger than or equal to sizeof(destination). The source buffer is larger than the destination buffer so there is the potential for overflowing the destination buffer.

Common Weakness Enumeration: 398

argumentSize
// cppcheck-suppress argumentSize

Message: The array ‘array’ is too small, the function ‘function’ expects a bigger one.

Common Weakness Enumeration: 39

arrayIndexOutOfBoundsCond
// cppcheck-suppress arrayIndexOutOfBoundsCond

Message: Array ‘x[10]’ accessed at index 20, which is out of bounds. Otherwise condition ‘y==20’ is redundant.

Common Weakness Enumeration: 119

ignoredReturnValue
// cppcheck-suppress ignoredReturnValue

Message: Return value of function malloc() is not used.

Common Weakness Enumeration: 25

wrongmathcall
// cppcheck-suppress wrongmathcall

Message: Passing value ‘#’ to #() leads to implementation-defined result.

Common Weakness Enumeration: 758

memsetZeroBytes
// cppcheck-suppress memsetZeroBytes

Message: memset() called to fill 0 bytes.

Verbose explanation: memset() called to fill 0 bytes. The second and third arguments might be inverted. The function memset ( void * ptr, int value, size_t num ) sets the first num bytes of the block of memory pointed by ptr to the specified value.

Common Weakness Enumeration: 687

memsetValueOutOfRange
// cppcheck-suppress memsetValueOutOfRange

Message: The 2nd memset() argument ‘varname’ doesn’t fit into an ‘unsigned char’.

Verbose explanation: The 2nd memset() argument ‘varname’ doesn’t fit into an ‘unsigned char’. The 2nd parameter is passed as an ‘int’, but the function fills the block of memory using the ‘unsigned char’ conversion of this value.

Common Weakness Enumeration: 686

uninitMemberVar
// cppcheck-suppress uninitMemberVar

Message: Member variable ‘classname::varname’ is not initialized in the constructor.

Verbose explanation: Member variable ‘classname::varname’ is not initialized in the constructor.

Common Weakness Enumeration: 39

operatorEqVarError
// cppcheck-suppress operatorEqVarError

Message: Member variable ‘classname::’ is not assigned a value in ‘classname::operator=’.

Common Weakness Enumeration: 39

mallocOnClassWarning
// cppcheck-suppress mallocOnClassWarning

Message: Memory for class instance allocated with malloc(), but class provides constructors.

Verbose explanation: Memory for class instance allocated with malloc(), but class provides constructors. This is unsafe, since no constructor is called and class members remain uninitialized. Consider using ‘new’ instead.

Common Weakness Enumeration: 76

thisSubtraction
// cppcheck-suppress thisSubtraction

Message: Suspicious pointer subtraction. Did you intend to write ‘->’?

Verbose explanation: Suspicious pointer subtraction. Did you intend to write ‘->’?

Common Weakness Enumeration: 398

operatorEqToSelf
// cppcheck-suppress operatorEqToSelf

Message: ‘operator=’ should check for assignment to self to avoid problems with dynamic memory.

Verbose explanation: ‘operator=’ should check for assignment to self to ensure that each block of dynamically allocated memory is owned and managed by only one instance of the class.

Common Weakness Enumeration: 398

duplInheritedMember
// cppcheck-suppress duplInheritedMember

Message: The class ‘class’ defines member variable with name ‘variable’ also defined in its parent class ‘class’.

Common Weakness Enumeration: 39

copyCtorAndEqOperator
// cppcheck-suppress copyCtorAndEqOperator

Message: The class ‘class’ has ‘operator=’ but lack of ‘copy constructor’.

pureVirtualCall
// cppcheck-suppress pureVirtualCall

Message: Call of pure virtual function ‘f’ in constructor.

Verbose explanation: Call of pure virtual function ‘f’ in constructor. The call will fail during runtime.”>

virtualCallInConstructor
// cppcheck-suppress virtualCallInConstructor

Message: Virtual function ‘f’ is called from constructor ‘’ at line 1. Dynamic binding is not used.

badBitmaskCheck
// cppcheck-suppress badBitmaskCheck

Message: Result of operator &#124; is always true if one operand is non-zero. Did you intend to use &?

Common Weakness Enumeration: 571

oppositeInnerCondition
// cppcheck-suppress oppositeInnerCondition

Message: Opposite inner ‘if’ condition leads to a dead code block.

Verbose explanation: Opposite inner ‘if’ condition leads to a dead code block (outer condition is ‘x’ and inner condition is ‘!x’).

Common Weakness Enumeration: 398

identicalInnerCondition
// cppcheck-suppress identicalInnerCondition

Message: Identical inner ‘if’ condition is always true.

Verbose explanation: Identical inner ‘if’ condition is always true (outer condition is ‘x’ and inner condition is ‘x’).

Common Weakness Enumeration: 398

identicalConditionAfterEarlyExit
// cppcheck-suppress identicalConditionAfterEarlyExit

Message: Identical condition ‘x’, second condition is always false

Common Weakness Enumeration: 398

incorrectLogicOperator
// cppcheck-suppress incorrectLogicOperator

Message: Logical disjunction always evaluates to true: foo > 3 && foo < 4.

Verbose explanation: Logical disjunction always evaluates to true: foo > 3 && foo < 4. Are these conditions necessary? Did you intend to use && instead? Are the numbers correct? Are you comparing the correct variables?

Common Weakness Enumeration: 571

moduloAlwaysTrueFalse
// cppcheck-suppress moduloAlwaysTrueFalse

Message: Comparison of modulo result is predetermined, because it is always less than 1.

Common Weakness Enumeration: 398

invalidTestForOverflow
// cppcheck-suppress invalidTestForOverflow

Message: Invalid test for overflow ‘x + u < x’. Condition is always false unless there is overflow, and overflow is undefined behaviour.

Common Weakness Enumeration: 570

pointerAdditionResultNotNull
// cppcheck-suppress pointerAdditionResultNotNull

Message: Comparison is wrong. Result of ‘ptr+1’ can’t be 0 unless there is pointer overflow, and pointer overflow is undefined behaviour.

exceptThrowInDestructor
// cppcheck-suppress exceptThrowInDestructor

Message: Class Class is not safe, destructor throws exception

Verbose explanation: The class Class is not safe because its destructor throws an exception. If Class is used and an exception is thrown that is caught in an outer scope the program will terminate.

Common Weakness Enumeration: 398

exceptDeallocThrow
// cppcheck-suppress exceptDeallocThrow

Message: Exception thrown in invalid state, ‘p’ points at deallocated memory.

Common Weakness Enumeration: 398

seekOnAppendedFile
// cppcheck-suppress seekOnAppendedFile

Message: Repositioning operation performed on a file opened in append mode has no effect.

Common Weakness Enumeration: 398

invalidscanf
// cppcheck-suppress invalidscanf

Message: scanf() without field width limits can crash with huge input data.

Verbose explanation: scanf() without field width limits can crash with huge input data. Add a field width specifier to fix this problem.

Sample program that can crash:

#include <stdio.h>
int main()
{
    char c[5];
    scanf("%s", c);
    return 0;
}

Typing in 5 or more characters may make the program crash. The correct usage here is scanf("%4s", c);, as the maximum field width does not include the terminating null byte.

Source:

http://linux.die.net/man/3/scanf

http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/libkern/stdio/scanf.c

Common Weakness Enumeration: 119

invalidScanfArgType_s
// cppcheck-suppress invalidScanfArgType_s

Message: %s in format string (no. 1) requires a ‘char *’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidScanfArgType_int
// cppcheck-suppress invalidScanfArgType_int

Message: %d in format string (no. 1) requires ‘int *’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidScanfArgType_float
// cppcheck-suppress invalidScanfArgType_float

Message: %f in format string (no. 1) requires ‘float *’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_s
// cppcheck-suppress invalidPrintfArgType_s

Message: %s in format string (no. 1) requires ‘char *’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_n
// cppcheck-suppress invalidPrintfArgType_n

Message: %n in format string (no. 1) requires ‘int *’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_p
// cppcheck-suppress invalidPrintfArgType_p

Message: %p in format string (no. 1) requires an address but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_uint
// cppcheck-suppress invalidPrintfArgType_uint

Message: %u in format string (no. 1) requires ‘unsigned int’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_sint
// cppcheck-suppress invalidPrintfArgType_sint

Message: %i in format string (no. 1) requires ‘int’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidPrintfArgType_float
// cppcheck-suppress invalidPrintfArgType_float

Message: %f in format string (no. 1) requires ‘double’ but the argument type is Unknown.

Common Weakness Enumeration: 686

invalidLengthModifierError
// cppcheck-suppress invalidLengthModifierError

Message: ‘I’ in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.

Common Weakness Enumeration: 704

wrongPrintfScanfParameterPositionError
// cppcheck-suppress wrongPrintfScanfParameterPositionError

Message: printf: referencing parameter 2 while 1 arguments given

Common Weakness Enumeration: 685

leakUnsafeArgAlloc
// cppcheck-suppress leakUnsafeArgAlloc

Message: Unsafe allocation. If funcName() throws, memory could be leaked. Use make_shared() instead.

Common Weakness Enumeration: 401

publicAllocationError
// cppcheck-suppress publicAllocationError

Message: Possible leak in public function. The pointer ‘varname’ is not deallocated before it is allocated.

Common Weakness Enumeration: 39

nullPointerDefaultArg
// cppcheck-suppress nullPointerDefaultArg

Message: Possible null pointer dereference if the default parameter value is used: pointer

Common Weakness Enumeration: 47

nullPointerRedundantCheck
// cppcheck-suppress nullPointerRedundantCheck

Message: Either the condition is redundant or there is possible null pointer dereference: pointer.

Common Weakness Enumeration: 47

comparisonFunctionIsAlwaysTrueOrFalse
// cppcheck-suppress comparisonFunctionIsAlwaysTrueOrFalse

Message: Comparison of two identical variables with isless(varName,varName) always evaluates to false.

Verbose explanation: The function isless is designed to compare two variables. Calling this function with one variable (varName) for both parameters leads to a statement which is always false.

Common Weakness Enumeration: 57

checkCastIntToCharAndBack
// cppcheck-suppress checkCastIntToCharAndBack

Message: Storing func_name() return value in char variable and then comparing with EOF.

Verbose explanation: When saving func_name() return value in char variable there is loss of precision. When func_name() returns EOF this value is truncated. Comparing the char variable with EOF can have unexpected results. For instance a loop while (EOF != (c = func_name()); loops forever on some compilers/platforms and on other compilers/platforms it will stop when the file contains a matching character.

Common Weakness Enumeration: 19

constStatement
// cppcheck-suppress constStatement

Message: Redundant code: Found a statement that begins with type constant.

Common Weakness Enumeration: 398

signedCharArrayIndex
// cppcheck-suppress signedCharArrayIndex

Message: Signed ‘char’ type used as array index.

Verbose explanation: Signed ‘char’ type used as array index. If the value can be greater than 127 there will be a buffer underflow because of sign extension.

Common Weakness Enumeration: 128

charBitOp
// cppcheck-suppress charBitOp

Message: When using ‘char’ variables in bit operations, sign extension can generate unexpected results.

Verbose explanation: When using ‘char’ variables in bit operations, sign extension can generate unexpected results. For example:

char c = 0x80;
int i = 0 | c;
if (i & 0x8000)
    printf("not expected");

The “not expected” will be printed on the screen.

Common Weakness Enumeration: 398

redundantAssignInSwitch
// cppcheck-suppress redundantAssignInSwitch

Message: Variable ‘var’ is reassigned a value before the old one has been used. ‘break;’ missing?

Verbose explanation: Variable ‘var’ is reassigned a value before the old one has been used. ‘break;’ missing?

Common Weakness Enumeration: 56

redundantCopyInSwitch
// cppcheck-suppress redundantCopyInSwitch

Message: Buffer ‘var’ is being written before its old content has been used. ‘break;’ missing?

Common Weakness Enumeration: 56

suspiciousCase
// cppcheck-suppress suspiciousCase

Message: Found suspicious case label in switch(). Operator &#124;&#124; probably doesn’t work as intended.

Verbose explanation: Using an operator like &#124;&#124; in a case label is suspicious. Did you intend to use a bitwise operator, multiple case labels or if/else instead?

Common Weakness Enumeration: 398

suspiciousEqualityComparison
// cppcheck-suppress suspiciousEqualityComparison

Message: Found suspicious equality comparison. Did you intend to assign a value instead?

Common Weakness Enumeration: 482

selfAssignment
// cppcheck-suppress selfAssignment

Message: Redundant assignment of ‘varname’ to itself.

Common Weakness Enumeration: 39

clarifyStatement
// cppcheck-suppress clarifyStatement

Message: Ineffective statement similar to ‘*A++;’. Did you intend to write ‘(*A)++;’?

Verbose explanation: A statement like ‘A++;’ might not do what you intended. Postfix ‘operator++’ is executed before ‘operator’. Thus, the dereference is meaningless. Did you intend to write ‘(*A)++;’?

Common Weakness Enumeration: 783

suspiciousSemicolon
// cppcheck-suppress suspiciousSemicolon

Message: Suspicious use of ; at the end of ‘’ statement.

Common Weakness Enumeration: 398

incompleteArrayFill
// cppcheck-suppress incompleteArrayFill

Message: Array ‘buffer’ is filled incompletely. Did you forget to multiply the size given to ‘memset()’ with ‘sizeof(*buffer)’?

Verbose explanation: The array ‘buffer’ is filled incompletely. The function ‘memset()’ needs the size given in bytes, but an element of the given array is larger than one byte. Did you forget to multiply the size with ‘sizeof(*buffer)’?

Common Weakness Enumeration: 131

unusedLabelSwitch
// cppcheck-suppress unusedLabelSwitch

Message: Label ‘’ is not used. Should this be a ‘case’ of the enclosing switch()?

Common Weakness Enumeration: 39

accessMoved
// cppcheck-suppress accessMoved

Message: Access of moved variable ‘v’.

Common Weakness Enumeration: 672

accessForwarded
// cppcheck-suppress accessForwarded

Message: Access of forwarded variable ‘v’.

Common Weakness Enumeration: 672

redundantBitwiseOperationInSwitch
// cppcheck-suppress redundantBitwiseOperationInSwitch

Message: Redundant bitwise operation on ‘varname’ in ‘switch’ statement. ‘break;’ missing?

funcArgOrderDifferent
// cppcheck-suppress funcArgOrderDifferent

Message: Function ‘function’ argument order different: declaration ‘’ definition ‘’

Common Weakness Enumeration: 68

mismatchingContainerExpression
// cppcheck-suppress mismatchingContainerExpression

Message: Iterators to containers from different expressions ‘v1’ and ‘v2’ are used together.

Common Weakness Enumeration: 664

stlIfFind
// cppcheck-suppress stlIfFind

Message: Suspicious condition. The result of find() is an iterator, but it is not properly checked.

Common Weakness Enumeration: 398

StlMissingComparison
// cppcheck-suppress StlMissingComparison

Message: Missing bounds check for extra iterator increment in loop.

Verbose explanation: The iterator incrementing is suspicious - it is incremented at line and then at line . The loop might unintentionally skip an element in the container. There is no comparison between these increments to prevent that the iterator is incremented beyond the end.

Common Weakness Enumeration: 834

uselessCallsCompare
// cppcheck-suppress uselessCallsCompare

Message: It is inefficient to call ‘str.find(str)’ as it always returns 0.

Verbose explanation: ‘std::string::find()’ returns zero when given itself as parameter (str.find(str)). As it is currently the code is inefficient. It is possible either the string searched (‘str’) or searched for (‘str’) is wrong.

Common Weakness Enumeration: 62

uselessCallsEmpty
// cppcheck-suppress uselessCallsEmpty

Message: Ineffective call of function ‘empty()’. Did you intend to call ‘clear()’ instead?

Common Weakness Enumeration: 398

uselessCallsRemove
// cppcheck-suppress uselessCallsRemove

Message: Return value of std::remove() ignored. Elements remain in container.

Verbose explanation: The return value of std::remove() is ignored. This function returns an iterator to the end of the range containing those elements that should be kept. Elements past new end remain valid but with unspecified values. Use the erase method of the container to delete them.

Common Weakness Enumeration: 76

derefInvalidIterator
// cppcheck-suppress derefInvalidIterator

Message: Possible dereference of an invalid iterator: i

Verbose explanation: Possible dereference of an invalid iterator: i. Make sure to check that the iterator is valid before dereferencing it - not after.

Common Weakness Enumeration: 82

sizeofwithsilentarraypointer
// cppcheck-suppress sizeofwithsilentarraypointer

Message: Using ‘sizeof’ on array given as function argument returns size of a pointer.

Verbose explanation: Using ‘sizeof’ for array given as function argument returns the size of a pointer. It does not return the size of the whole array in bytes as might be expected. For example, this code: int f(char a[100]) { return sizeof(a); } returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the size of the array in bytes).

Common Weakness Enumeration: 467

pointerSize
// cppcheck-suppress pointerSize

Message: Size of pointer ‘varname’ used instead of size of its data.

Verbose explanation: Size of pointer ‘varname’ used instead of size of its data. This is likely to lead to a buffer overflow. You probably intend to write ‘sizeof(*varname)’.

Common Weakness Enumeration: 467

sizeofDivisionMemfunc
// cppcheck-suppress sizeofDivisionMemfunc

Message: Division by result of sizeof(). memset() expects a size in bytes, did you intend to multiply instead?

Common Weakness Enumeration: 682

sizeofwithnumericparameter
// cppcheck-suppress sizeofwithnumericparameter

Message: Suspicious usage of ‘sizeof’ with a numeric constant as parameter.

Verbose explanation: It is unusual to use a constant value with sizeof. For example, ‘sizeof(10)’ returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10. ‘sizeof(‘A’)’ and ‘sizeof(char)’ can return different results.

Common Weakness Enumeration: 682

sizeofsizeof
// cppcheck-suppress sizeofsizeof

Message: Calling ‘sizeof’ on ‘sizeof’.

Verbose explanation: Calling sizeof for ‘sizeof looks like a suspicious code and most likely there should be just one ‘sizeof’. The current code is equivalent to ‘sizeof(size_t)’

Common Weakness Enumeration: 682

sizeofCalculation
// cppcheck-suppress sizeofCalculation

Message: Found calculation inside sizeof().

Common Weakness Enumeration: 682

sizeofFunctionCall
// cppcheck-suppress sizeofFunctionCall

Message: Found function call inside sizeof().

Common Weakness Enumeration: 682

multiplySizeof
// cppcheck-suppress multiplySizeof

Message: Multiplying sizeof() with sizeof() indicates a logic error.

Common Weakness Enumeration: 682

divideSizeof
// cppcheck-suppress divideSizeof

Message: Division of result of sizeof() on pointer type.

Verbose explanation: Division of result of sizeof() on pointer type. sizeof() returns the size of the pointer, not the size of the memory area it points to.

Common Weakness Enumeration: 682

incorrectStringCompare
// cppcheck-suppress incorrectStringCompare

Message: String literal “Hello World” doesn’t match length argument for substr().

Common Weakness Enumeration: 57

literalWithCharPtrCompare
// cppcheck-suppress literalWithCharPtrCompare

Message: String literal compared with variable ‘foo’. Did you intend to use strcmp() instead?

Common Weakness Enumeration: 59

charLiteralWithCharPtrCompare
// cppcheck-suppress charLiteralWithCharPtrCompare

Message: Char literal compared with pointer ‘foo’. Did you intend to dereference it?

Common Weakness Enumeration: 59

incorrectStringBooleanError
// cppcheck-suppress incorrectStringBooleanError

Message: Conversion of string literal “Hello World” to bool always evaluates to true.

Common Weakness Enumeration: 571

incorrectCharBooleanError
// cppcheck-suppress incorrectCharBooleanError

Message: Conversion of char literal ‘x’ to bool always evaluates to true.

Common Weakness Enumeration: 571

staticStringCompare
// cppcheck-suppress staticStringCompare

Message: Unnecessary comparison of static strings.

Verbose explanation: The compared strings, ‘str1’ and ‘str2’, are always unequal. Therefore the comparison is unnecessary and looks suspicious.

Common Weakness Enumeration: 570

stringCompare
// cppcheck-suppress stringCompare

Message: Comparison of identical string variables.

Verbose explanation: The compared strings, ‘varname1’ and ‘varname2’, are identical. This could be a logic bug.

Common Weakness Enumeration: 571

overlappingStrcmp
// cppcheck-suppress overlappingStrcmp

Message: The expression ‘strcmp(x,”def”) != 0’ is suspicious. It overlaps ‘strcmp(x,”abc”) == 0’.

signConversion
// cppcheck-suppress signConversion

Message: Suspicious code: sign conversion of var in calculation, even though var can have a negative value

Common Weakness Enumeration: 19

va_start_wrongParameter
// cppcheck-suppress va_start_wrongParameter

Message: ‘arg1’ given to va_start() is not last named argument of the function. Did you intend to pass ‘arg2’?

Common Weakness Enumeration: 688

Portability

AssignmentAddressToInteger
// cppcheck-suppress AssignmentAddressToInteger

Message: Assigning a pointer to an integer is not portable.

Verbose explanation: Assigning a pointer to an integer (int/long/etc) is not portable across different platforms and compilers. For example in 32-bit Windows and linux they are same width, but in 64-bit Windows and linux they are of different width. In worst case you end up assigning 64-bit address to 32-bit integer. The safe way is to store addresses only in pointer types (or typedefs like uintptr_t).

Common Weakness Enumeration: 758

AssignmentIntegerToAddress
// cppcheck-suppress AssignmentIntegerToAddress

Message: Assigning an integer to a pointer is not portable.

Verbose explanation: Assigning an integer (int/long/etc) to a pointer is not portable across different platforms and compilers. For example in 32-bit Windows and linux they are same width, but in 64-bit Windows and linux they are of different width. In worst case you end up assigning 64-bit integer to 32-bit pointer. The safe way is to store addresses only in pointer types (or typedefs like uintptr_t).

Common Weakness Enumeration: 758

CastIntegerToAddressAtReturn
// cppcheck-suppress CastIntegerToAddressAtReturn

Message: Returning an integer in a function with pointer return type is not portable.

Verbose explanation: Returning an integer (int/long/etc) in a function with pointer return type is not portable across different platforms and compilers. For example in 32-bit Windows and Linux they are same width, but in 64-bit Windows and Linux they are of different width. In worst case you end up casting 64-bit integer down to 32-bit pointer. The safe way is to always return a pointer.

Common Weakness Enumeration: 758

CastAddressToIntegerAtReturn
// cppcheck-suppress CastAddressToIntegerAtReturn

Message: Returning an address value in a function with integer return type is not portable.

Verbose explanation: Returning an address value in a function with integer (int/long/etc) return type is not portable across different platforms and compilers. For example in 32-bit Windows and Linux they are same width, but in 64-bit Windows and Linux they are of different width. In worst case you end up casting 64-bit address down to 32-bit integer. The safe way is to always return an integer.

Common Weakness Enumeration: 758

pointerOutOfBounds
// cppcheck-suppress pointerOutOfBounds

Message: Undefined behaviour, pointer arithmetic ‘’ is out of bounds.

Verbose explanation: Undefined behaviour, pointer arithmetic ‘’ is out of bounds. From chapter 6.5.6 in the C specification: “When an expression that has integer type is added to or subtracted from a pointer, ..” and then “If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.”

Common Weakness Enumeration: 398

memsetFloat
// cppcheck-suppress memsetFloat

Message: The 2nd memset() argument ‘varname’ is a float, its representation is implementation defined.

Verbose explanation: The 2nd memset() argument ‘varname’ is a float, its representation is implementation defined. memset() is used to set each byte of a block of memory to a specific value and the actual representation of a floating-point value is implementation defined.

Common Weakness Enumeration: 688

memsetClassFloat
// cppcheck-suppress memsetClassFloat

Message: Using memset() on class which contains a floating point number.

Verbose explanation: Using memset() on class which contains a floating point number. This is not portable because memset() sets each byte of a block of memory to a specific value and the actual representation of a floating-point value is implementation defined. Note: In case of an IEEE754-1985 compatible implementation setting all bits to zero results in the value 0.0.

Common Weakness Enumeration: 758

fflushOnInputStream
// cppcheck-suppress fflushOnInputStream

Message: fflush() called on input stream ‘stdin’ may result in undefined behaviour on non-linux systems.

Common Weakness Enumeration: 398

invalidPointerCast
// cppcheck-suppress invalidPointerCast

Message: Casting between float* and double* which have an incompatible binary data representation.

Common Weakness Enumeration: 704

shiftNegativeLHS
// cppcheck-suppress shiftNegativeLHS

Message: Shifting a negative value is technically undefined behaviour

Common Weakness Enumeration: 758

unknownSignCharArrayIndex
// cppcheck-suppress unknownSignCharArrayIndex

Message: ‘char’ type used as array index.

Verbose explanation: ‘char’ type used as array index. Values greater that 127 will be treated depending on whether ‘char’ is signed or unsigned on target platform.

Common Weakness Enumeration: 758

varFuncNullUB
// cppcheck-suppress varFuncNullUB

Message: Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.

Verbose explanation: Passing NULL after the last typed argument to a variadic function leads to undefined behaviour. The C99 standard, in section 7.15.1.1, states that if the type used by va_arg() is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined. The value of the NULL macro is an implementation-defined null pointer constant (7.17), which can be any integer constant expression with the value 0, or such an expression casted to (void*) (6.3.2.3). This includes values like 0, 0L, or even 0LL. In practice on common architectures, this will cause real crashes if sizeof(int) != sizeof(void*), and NULL is defined to 0 or any other null pointer constant that promotes to int. To reproduce you might be able to use this little code example on 64bit platforms. If the output includes “ERROR”, the sentinel had only 4 out of 8 bytes initialized to zero and was not detected as the final argument to stop argument processing via va_arg(). Changing the 0 to (void*)0 or 0L will make the “ERROR” output go away.

#include <stdarg.h>
#include <stdio.h>

void f(char *s, ...) {
    va_list ap;
    va_start(ap,s);
    for (;;) {
        char *p = va_arg(ap,char*);
        printf("%018p, %s\n", p, (long)p & 255 ? p : "");
        if(!p) break;
    }
    va_end(ap);
}

void g() {
    char *s2 = "x";
    char *s3 = "ERROR";

    // changing 0 to 0L for the 7th argument (which is intended to act as sentinel) makes the error go away on x86_64
    f("first", s2, s2, s2, s2, s2, 0, s3, (char*)0);
}

void h() {
    int i;
    volatile unsigned char a[1000];
    for (i = 0; i<sizeof(a); i++)
        a[i] = -1;
}

int main() {
    h();
    g();
    return 0;
}

Common Weakness Enumeration: 475

sizeofVoid
// cppcheck-suppress sizeofVoid

Message: Behaviour of ‘sizeof(void)’ is not covered by the ISO C standard.

Verbose explanation: Behaviour of ‘sizeof(void)’ is not covered by the ISO C standard. A value for ‘sizeof(void)’ is defined only as part of a GNU C extension, which defines ‘sizeof(void)’ to be 1.

Common Weakness Enumeration: 682

sizeofDereferencedVoidPointer
// cppcheck-suppress sizeofDereferencedVoidPointer

Message: ‘*varname’ is of type ‘void’, the behaviour of ‘sizeof(void)’ is not covered by the ISO C standard.

Verbose explanation: ‘*varname’ is of type ‘void’, the behaviour of ‘sizeof(void)’ is not covered by the ISO C standard. A value for ‘sizeof(void)’ is defined only as part of a GNU C extension, which defines ‘sizeof(void)’ to be 1.

Common Weakness Enumeration: 682

arithOperationsOnVoidPointer
// cppcheck-suppress arithOperationsOnVoidPointer

Message: ‘varname’ is of type ‘vartype’. When using void pointers in calculations, the behaviour is undefined.

Verbose explanation: ‘varname’ is of type ‘vartype’. When using void pointers in calculations, the behaviour is undefined. Arithmetic operations on ‘void *’ is a GNU C extension, which defines the ‘sizeof(void)’ to be 1.

Common Weakness Enumeration: 46

Performance

useInitializationList
// cppcheck-suppress useInitializationList

Message: Variable ‘variable’ is assigned in constructor body. Consider performing initialization in initialization list.

Verbose explanation: When an object of a class is created, the constructors of all member variables are called consecutively in the order the variables are declared, even if you don’t explicitly write them to the initialization list. You could avoid assigning ‘variable’ a value by passing the value to the constructor in the initialization list.

Common Weakness Enumeration: 39

functionStatic
// cppcheck-suppress functionStatic

Message: Technically the member function ‘class::function’ can be static (but you may consider moving to unnamed namespace).

Verbose explanation: The member function ‘class::function’ can be made a static function. Making a function static can bring a performance benefit since no ‘this’ instance is passed to the function. This change should not cause compiler errors but it does not necessarily make sense conceptually. Think about your design and the task of the function first - is it a function that must not access members of class instances? And maybe it is more appropriate to move this function to a unnamed namespace.

Common Weakness Enumeration: 398

redundantCopyLocalConst
// cppcheck-suppress redundantCopyLocalConst

Message: Use const reference for ‘varname’ to avoid unnecessary data copying.

Verbose explanation: The const variable ‘varname’ is assigned a copy of the data. You can avoid the unnecessary data copying by converting ‘varname’ to const reference.

Common Weakness Enumeration: 398

redundantCopy
// cppcheck-suppress redundantCopy

Message: Buffer ‘var’ is being written before its old content has been used.

Common Weakness Enumeration: 56

passedByValue
// cppcheck-suppress passedByValue

Message: Function parameter ‘parametername’ should be passed by const reference.

Verbose explanation: Parameter ‘parametername’ is passed by value. It could be passed as a const reference which is usually faster and recommended in C++.

Common Weakness Enumeration: 39

stlIfStrFind
// cppcheck-suppress stlIfStrFind

Message: Inefficient usage of string::find() in condition; string::compare() would be faster.

Verbose explanation: Either inefficient or wrong usage of string::find(). string::compare() will be faster if string::find’s result is compared with 0, because it will not scan the whole string. If your intention is to check that there are no findings in the string, you should compare with std::string::npos.

Common Weakness Enumeration: 597

stlcstrReturn
// cppcheck-suppress stlcstrReturn

Message: Returning the result of c_str() in a function that returns std::string is slow and redundant.

Verbose explanation: The conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly returning the string.

Common Weakness Enumeration: 704

stlcstrParam
// cppcheck-suppress stlcstrParam

Message: Passing the result of c_str() to a function that takes std::string as argument no. 0 is slow and redundant.

Verbose explanation: The conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly passing the string.

Common Weakness Enumeration: 704

stlSize
// cppcheck-suppress stlSize

Message: Possible inefficient checking for ‘list’ emptiness.

Verbose explanation: Checking for ‘list’ emptiness might be inefficient. Using list.empty() instead of list.size() can be faster. list.size() can take linear time but list.empty() is guaranteed to take constant time.

Common Weakness Enumeration: 39

uselessCallsSwap
// cppcheck-suppress uselessCallsSwap

Message: It is inefficient to swap a object with itself by calling ‘str.swap(str)’

Verbose explanation: The ‘swap()’ function has no logical effect when given itself as parameter (str.swap(str)). As it is currently the code is inefficient. Is the object or the parameter wrong here?

Common Weakness Enumeration: 62

uselessCallsSubstr
// cppcheck-suppress uselessCallsSubstr

Message: Ineffective call of function ‘substr’ because it returns a copy of the object. Use operator= instead.

Common Weakness Enumeration: 398

postfixOperator
// cppcheck-suppress postfixOperator

Message: Prefer prefix ++/– operators for non-primitive types.

Verbose explanation: Prefix ++/– operators should be preferred for non-primitive types. Pre-increment/decrement can be more efficient than post-increment/decrement. Post-increment/decrement usually involves keeping a copy of the previous value around and adds a little extra code.

Common Weakness Enumeration: 398

Information

purgedConfiguration
// cppcheck-suppress purgedConfiguration

Message: The configuration ‘’ was not checked because its code equals another one.

toomanyconfigs
// cppcheck-suppress toomanyconfigs

Message: Too many #ifdef configurations - cppcheck only checks 12 configurations. Use –force to check all configurations. For more details, use –enable=information.

Verbose explanation: The checking of the file will be interrupted because there are too many #ifdef configurations. Checking of all #ifdef configurations can be forced by –force command line option or from GUI preferences. However that may increase the checking time. For more details, use –enable=information.

Common Weakness Enumeration: 398

missingInclude
// cppcheck-suppress missingInclude

Message: Include file: “” not found.

missingIncludeSystem
// cppcheck-suppress missingIncludeSystem

Message: Include file: <> not found. Please note: Cppcheck does not need standard library headers to get proper results.

ConfigurationNotChecked
// cppcheck-suppress ConfigurationNotChecked

Message: Skipping configuration ‘X’ since the value of ‘X’ is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.

Style

uselessAssignmentArg
// cppcheck-suppress uselessAssignmentArg

Message: Assignment of function parameter has no effect outside the function.

Common Weakness Enumeration: 398

assignBoolToFloat
// cppcheck-suppress assignBoolToFloat

Message: Boolean value assigned to floating point variable.

Common Weakness Enumeration: 704

comparisonOfFuncReturningBoolError
// cppcheck-suppress comparisonOfFuncReturningBoolError

Message: Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.

Verbose explanation: The return type of function ‘func_name’ is ‘bool’ and result is of type ‘bool’. Comparing ‘bool’ value using relational (<, >, <= or >=) operator could cause unexpected results.

Common Weakness Enumeration: 398

comparisonOfTwoFuncsReturningBoolError
// cppcheck-suppress comparisonOfTwoFuncsReturningBoolError

Message: Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.

Verbose explanation: The return type of function ‘func_name1’ and function ‘func_name2’ is ‘bool’ and result is of type ‘bool’. Comparing ‘bool’ value using relational (<, >, <= or >=) operator could cause unexpected results.

Common Weakness Enumeration: 398

comparisonOfBoolWithBoolError
// cppcheck-suppress comparisonOfBoolWithBoolError

Message: Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.

Verbose explanation: The variable ‘var_name’ is of type ‘bool’ and comparing ‘bool’ value using relational (<, >, <= or >=) operator could cause unexpected results.

Common Weakness Enumeration: 398

incrementboolean
// cppcheck-suppress incrementboolean

Message: Incrementing a variable of type ‘bool’ with postfix operator++ is deprecated by the C++ Standard. You should assign it the value ‘true’ instead.

Verbose explanation: The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value ‘true’ instead.

Common Weakness Enumeration: 398

bitwiseOnBoolean
// cppcheck-suppress bitwiseOnBoolean

Message: Boolean variable ‘varname’ is used in bitwise operation. Did you mean ‘&&’?

Common Weakness Enumeration: 398

returnNonBoolInBooleanFunction
// cppcheck-suppress returnNonBoolInBooleanFunction

Message: Non-boolean value returned from function returning bool

arrayIndexThenCheck
// cppcheck-suppress arrayIndexThenCheck

Message: Array index ‘index’ is used before limits check.

Verbose explanation: Defensive programming: The variable ‘index’ is used as an array index before it is checked that is within limits. This can mean that the array might be accessed out of bounds. Reorder conditions such as ‘(a[i] && i < 10)’ to ‘(i < 10 && a[i])’. That way the array will not be accessed if the index is out of limits.

Common Weakness Enumeration: 39

unpreciseMathCall
// cppcheck-suppress unpreciseMathCall

Message: Expression ‘1 - erf(x)’ can be replaced by ‘erfc(x)’ to avoid loss of precision.

Common Weakness Enumeration: 758

noConstructor
// cppcheck-suppress noConstructor

Message: The class ‘classname’ does not have a constructor although it has private member variables.

Verbose explanation: The class ‘classname’ does not have a constructor although it has private member variables. Member variables of builtin types are left uninitialized when the class is instantiated. That may cause bugs or undefined behavior.

Common Weakness Enumeration: 39

noExplicitConstructor
// cppcheck-suppress noExplicitConstructor

Message: Class ‘classname’ has a constructor with 1 argument that is not explicit.

Verbose explanation: Class ‘classname’ has a constructor with 1 argument that is not explicit. Such constructors should in general be explicit for type safety reasons. Using the explicit keyword in the constructor means some mistakes when using the class can be avoided.

Common Weakness Enumeration: 39

copyCtorPointerCopying
// cppcheck-suppress copyCtorPointerCopying

Message: Value of pointer ‘var’, which points to allocated memory, is copied in copy constructor instead of allocating new memory.

Common Weakness Enumeration: 39

noCopyConstructor
// cppcheck-suppress noCopyConstructor

Message: Class ‘class’ does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).

Common Weakness Enumeration: 39

noOperatorEq
// cppcheck-suppress noOperatorEq

Message: Class ‘class’ does not have a operator= which is recommended since it has dynamic memory/resource allocation(s).

Common Weakness Enumeration: 39

noDestructor
// cppcheck-suppress noDestructor

Message: Class ‘class’ does not have a destructor which is recommended since it has dynamic memory/resource allocation(s).

Common Weakness Enumeration: 39

unusedPrivateFunction
// cppcheck-suppress unusedPrivateFunction

Message: Unused private function: ‘classname::funcname’

Common Weakness Enumeration: 39

operatorEq
// cppcheck-suppress operatorEq

Message: ‘class::operator=’ should return ‘class &’.

Verbose explanation: The class::operator= does not conform to standard C/C++ behaviour. To conform to standard C/C++ behaviour, return a reference to self (such as: ‘class &class::operator=(..) { .. return *this; }’. For safety reasons it might be better to not fix this message. If you think that safety is always more important than conformance then please ignore/suppress this message. For more details about this topic, see the book “Effective C++” by Scott Meyers.

Common Weakness Enumeration: 39

operatorEqRetRefThis
// cppcheck-suppress operatorEqRetRefThis

Message: ‘operator=’ should return reference to ‘this’ instance.

Common Weakness Enumeration: 398

operatorEqShouldBeLeftUnimplemented
// cppcheck-suppress operatorEqShouldBeLeftUnimplemented

Message: ‘operator=’ should either return reference to ‘this’ instance or be declared private and left unimplemented.

Common Weakness Enumeration: 398

functionConst
// cppcheck-suppress functionConst

Message: Technically the member function ‘class::function’ can be const.

Verbose explanation: The member function ‘class::function’ can be made a const function. Making this function ‘const’ should not cause compiler errors. Even though the function can be made const function technically it may not make sense conceptually. Think about your design and the task of the function first - is it a function that must not change object internal state?

Common Weakness Enumeration: 398

unsafeClassDivZero
// cppcheck-suppress unsafeClassDivZero

Message: Public interface of Class is not safe. When calling Class::dostuff(), if parameter x is 0 that leads to division by zero.

initializerList
// cppcheck-suppress initializerList

Message: Member variable ‘class::variable’ is in the wrong place in the initializer list.

Verbose explanation: Member variable ‘class::variable’ is in the wrong place in the initializer list. Members are initialized in the order they are declared, not in the order they are in the initializer list. Keeping the initializer list in the same order that the members were declared prevents order dependent initialization errors.

Common Weakness Enumeration: 398

missingOverride
// cppcheck-suppress missingOverride

Message: The function ‘’ overrides a function in a base class but is not marked with a ‘override’ specifier.

assignIfError
// cppcheck-suppress assignIfError

Message: Mismatching assignment and comparison, comparison ‘’ is always false.

Common Weakness Enumeration: 398

comparisonError
// cppcheck-suppress comparisonError

Message: Expression ‘(X & 0x6) == 0x1’ is always false.

Verbose explanation: The expression ‘(X & 0x6) == 0x1’ is always false. Check carefully constants and operators used, these errors might be hard to spot sometimes. In case of complex expression it might help to split it to separate expressions.

Common Weakness Enumeration: 398

multiCondition
// cppcheck-suppress multiCondition

Message: Expression is always false because ‘else if’ condition matches previous condition at line 1.

Common Weakness Enumeration: 398

mismatchingBitAnd
// cppcheck-suppress mismatchingBitAnd

Message: Mismatching bitmasks. Result is always 0 (X = Y & 0xf0; Z = X & 0x1; => Z=0).

Common Weakness Enumeration: 398

redundantCondition
// cppcheck-suppress redundantCondition

Message: Redundant condition: If x > 11 the condition x > 10 is always true.

Common Weakness Enumeration: 398

clarifyCondition
// cppcheck-suppress clarifyCondition

Message: Suspicious condition (assignment + comparison); Clarify expression with parentheses.

Common Weakness Enumeration: 398

knownConditionTrueFalse
// cppcheck-suppress knownConditionTrueFalse

Message: Condition ‘x’ is always false

Common Weakness Enumeration: 570

exceptRethrowCopy
// cppcheck-suppress exceptRethrowCopy

Message: Throwing a copy of the caught exception instead of rethrowing the original exception.

Verbose explanation: Rethrowing an exception with ‘throw varname;’ creates an unnecessary copy of ‘varname’. To rethrow the caught exception without unnecessary copying or slicing, use a bare ‘throw;’.

Common Weakness Enumeration: 398

catchExceptionByValue
// cppcheck-suppress catchExceptionByValue

Message: Exception should be caught by reference.

Verbose explanation: The exception is caught by value. It could be caught as a (const) reference which is usually recommended in C++.

Common Weakness Enumeration: 398

unhandledExceptionSpecification
// cppcheck-suppress unhandledExceptionSpecification

Message: Unhandled exception specification when calling function foo().

Verbose explanation: Unhandled exception specification when calling function foo(). Either use a try/catch around the function call, or add a exception specification for funcname() also.

Common Weakness Enumeration: 703

unsafeClassCanLeak
// cppcheck-suppress unsafeClassCanLeak

Message: Class ‘class’ is unsafe, ‘class::varname’ can leak by wrong usage.

Verbose explanation: The class ‘class’ is unsafe, wrong usage can cause memory/resource leaks for ‘class::varname’. This can for instance be fixed by adding proper cleanup in the destructor.

Common Weakness Enumeration: 39

unusedScopedObject
// cppcheck-suppress unusedScopedObject

Message: Instance of ‘varname’ object is destroyed immediately.

Common Weakness Enumeration: 56

redundantAssignment
// cppcheck-suppress redundantAssignment

Message: Variable ‘var’ is reassigned a value before the old one has been used.

Common Weakness Enumeration: 56

cstyleCast
// cppcheck-suppress cstyleCast

Message: C-style pointer casting

Verbose explanation: C-style pointer casting detected. C++ offers four different kinds of casts as replacements: static_cast, const_cast, dynamic_cast and reinterpret_cast. A C-style cast could evaluate to any of those automatically, thus it is considered safer if the programmer explicitly states which kind of cast is expected. See also: https://wiki.sei.cmu.edu/confluence/display/c/EXP05-C.+Do+not+cast+away+a+const+qualification

Common Weakness Enumeration: 398

variableScope
// cppcheck-suppress variableScope

Message: The scope of the variable ‘varname’ can be reduced.

Verbose explanation: The scope of the variable ‘varname’ can be reduced. Warning: Be careful when fixing this message, especially when there are inner loops. Here is an example where cppcheck will write that the scope for ‘i’ can be reduced:

void f(int x)
{
    int i = 0;
    if (x) {
        // it's safe to move 'int i = 0;' here
        for (int n = 0; n < 10; ++n) {
            // it is possible but not safe to move 'int i = 0;' here
            do_something(&i);
        }
    }
}

When you see this message it is always safe to reduce the variable scope 1 level.

Common Weakness Enumeration: 39

clarifyCalculation
// cppcheck-suppress clarifyCalculation

Message: Clarify calculation precedence for ‘+’ and ‘?’.

Verbose explanation: Suspicious calculation. Please use parentheses to clarify the code. The code a+b?c:d should be written as either (a+b)?c:d or a+(b?c:d).

Common Weakness Enumeration: 783

duplicateBranch
// cppcheck-suppress duplicateBranch

Message: Found duplicate branches for ‘if’ and ‘else’.

Verbose explanation: Finding the same code in an ‘if’ and related ‘else’ branch is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.

Common Weakness Enumeration: 398

duplicateAssignExpression
// cppcheck-suppress duplicateAssignExpression

Message: Same expression used in consecutive assignments of ‘x’ and ‘x’.

Verbose explanation: Finding variables ‘x’ and ‘x’ that are assigned the same expression is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.

Common Weakness Enumeration: 398

oppositeExpression
// cppcheck-suppress oppositeExpression

Message: Opposite expression on both sides of ‘&&’.

Verbose explanation: Finding the opposite expression on both sides of an operator is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.

Common Weakness Enumeration: 398

duplicateExpression
// cppcheck-suppress duplicateExpression

Message: Same expression on both sides of ‘&&’.

Verbose explanation: Finding the same expression on both sides of an operator is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.

Common Weakness Enumeration: 398

duplicateValueTernary
// cppcheck-suppress duplicateValueTernary

Message: Same value in both branches of ternary operator.

Verbose explanation: Finding the same value in both branches of ternary operator is suspicious as the same code is executed regardless of the condition.

Common Weakness Enumeration: 398

duplicateExpressionTernary
// cppcheck-suppress duplicateExpressionTernary

Message: Same expression in both branches of ternary operator.

Verbose explanation: Finding the same expression in both branches of ternary operator is suspicious as the same code is executed regardless of the condition.

Common Weakness Enumeration: 398

duplicateBreak
// cppcheck-suppress duplicateBreak

Message: Consecutive return, break, continue, goto or throw statements are unnecessary.

Verbose explanation: Consecutive return, break, continue, goto or throw statements are unnecessary. The second statement can never be executed, and so should be removed.

Common Weakness Enumeration: 561

unreachableCode
// cppcheck-suppress unreachableCode

Message: Statements following return, break, continue, goto or throw will never be executed.

Common Weakness Enumeration: 561

unsignedLessThanZero
// cppcheck-suppress unsignedLessThanZero

Message: Checking if unsigned variable ‘varname’ is less than zero.

Common Weakness Enumeration: 57

unsignedPositive
// cppcheck-suppress unsignedPositive

Message: Unsigned variable ‘varname’ can’t be negative so it is unnecessary to test it.

Common Weakness Enumeration: 57

pointerLessThanZero
// cppcheck-suppress pointerLessThanZero

Message: A pointer can not be negative so it is either pointless or an error to check if it is.

Common Weakness Enumeration: 570

pointerPositive
// cppcheck-suppress pointerPositive

Message: A pointer can not be negative so it is either pointless or an error to check if it is not.

Common Weakness Enumeration: 570

nanInArithmeticExpression
// cppcheck-suppress nanInArithmeticExpression

Message: Using NaN/Inf in a computation.

Verbose explanation: Using NaN/Inf in a computation. Although nothing bad really happens, it is suspicious.

Common Weakness Enumeration: 369

commaSeparatedReturn
// cppcheck-suppress commaSeparatedReturn

Message: Comma is used in return statement. The comma can easily be misread as a ‘;’.

Verbose explanation: Comma is used in return statement. When comma is used in a return statement it can easily be misread as a semicolon. For example in the code below the value of ‘b’ is returned if the condition is true, but it is easy to think that ‘a+1’ is returned: if (x) return a + 1, b++; However it can be useful to use comma in macros. Cppcheck does not warn when such a macro is then used in a return statement, it is less likely such code is misunderstood.

Common Weakness Enumeration: 398

redundantPointerOp
// cppcheck-suppress redundantPointerOp

Message: Redundant pointer operation on ‘varname’ - it’s already a pointer.

Common Weakness Enumeration: 39

unusedLabel
// cppcheck-suppress unusedLabel

Message: Label ‘’ is not used.

Common Weakness Enumeration: 39

funcArgNamesDifferent
// cppcheck-suppress funcArgNamesDifferent

Message: Function ‘function’ argument 2 names different: declaration ‘A’ definition ‘B’.

Common Weakness Enumeration: 628

shadowFunction
// cppcheck-suppress shadowFunction

Message: Local variable f shadows outer function

Common Weakness Enumeration: 39

shadowVar
// cppcheck-suppress shadowVar

Message: Local variable var shadows outer variable

Common Weakness Enumeration: 39

sameIteratorExpression
// cppcheck-suppress sameIteratorExpression

Message: Same iterators expression are used for algorithm.

Common Weakness Enumeration: 664

redundantIfRemove
// cppcheck-suppress redundantIfRemove

Message: Redundant checking of STL container element existence before removing it.

Verbose explanation: Redundant checking of STL container element existence before removing it. It is safe to call the remove method on a non-existing element.

Common Weakness Enumeration: 398

useAutoPointerCopy
// cppcheck-suppress useAutoPointerCopy

Message: Copying ‘auto_ptr’ pointer to another does not create two equal objects since one has lost its ownership of the pointer.

Verbose explanation: ‘std::auto_ptr’ has semantics of strict ownership, meaning that the ‘auto_ptr’ instance is the sole entity responsible for the object’s lifetime. If an ‘auto_ptr’ is copied, the source looses the reference.

Common Weakness Enumeration: 398

reademptycontainer
// cppcheck-suppress reademptycontainer

Message: Reading from empty STL container ‘var’

Common Weakness Enumeration: 398

useStlAlgorithm
// cppcheck-suppress useStlAlgorithm

Message: Consider using algorithm instead of a raw loop.

Common Weakness Enumeration: 398

truncLongCastAssignment
// cppcheck-suppress truncLongCastAssignment

Message: int result is assigned to long variable. If the variable is long to avoid loss of information, then you have loss of information.

Verbose explanation: int result is assigned to long variable. If the variable is long to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to long, for example ‘l = a * b;’ => ‘l = (long)a * b;’.

Common Weakness Enumeration: 197

truncLongCastReturn
// cppcheck-suppress truncLongCastReturn

Message: int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information.

Verbose explanation: int result is returned as long value. If the return value is long to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to long, for example ‘return ab;’ => ‘return (long)ab’.

Common Weakness Enumeration: 197

unusedFunction
// cppcheck-suppress unusedFunction

Message: The function ‘funcName’ is never used.

Common Weakness Enumeration: 56

unusedVariable
// cppcheck-suppress unusedVariable

Message: Unused variable: varname

Common Weakness Enumeration: 56

unusedAllocatedMemory
// cppcheck-suppress unusedAllocatedMemory

Message: Variable ‘varname’ is allocated memory that is never used.

Common Weakness Enumeration: 56

unreadVariable
// cppcheck-suppress unreadVariable

Message: Variable ‘varname’ is assigned a value that is never used.

Common Weakness Enumeration: 56

unassignedVariable
// cppcheck-suppress unassignedVariable

Message: Variable ‘varname’ is not assigned a value.

Common Weakness Enumeration: 66

unusedStructMember
// cppcheck-suppress unusedStructMember

Message: struct member ‘structname::variable’ is never used.

Common Weakness Enumeration: 56