facebook pixelC and C++ Static Code Analysis Rules
BACK TO LIST

C / C++ rules

C and C++ are really performant languages and can be very error-prone. We all had core dumps and made pointer arithmetic errors! Thankfully, Codiga has hundreds of static analysis rules to flag potential errors in your C/C++ code, automate code reviews and merge with confidence.

accessForwarded

Safety
High

Access of forwarded variable

accessMoved

Best practice
High

Access of moved variable.

allocaCalled

Best practice
High

Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.

arithOperationsOnVoidPointer

Best practice
Medium

Avoid arithmetic operation on void pointers

arrayIndexOutOfBounds

Safety
Critical

Array accessed out of bounds

arrayIndexOutOfBoundsCond

Best practice
High

Array access out of bounds with a conditions

arrayIndexThenCheck

Code style
Minor

Access array beyond boundaries

asctime_sCalled

Best practice
High

Obsolete function 'asctime_s' called. It is recommended to use 'strftime' instead.

asctimeCalled

Code style
Minor

Obsolete function 'std::asctime' called. It is recommended to use 'strftime' instead.

assertWithSideEffect

Best practice
High

Assert statement calls a function which may have desired side effects: 'IsAddressInSegment'.

assignBoolToFloat

Safety
Minor

Boolean value assigned to floating point variable.

assignBoolToPointer

Security
Critical

Boolean value assigned to pointer.

assignIfError

Error prone
Minor

Mismatching assignment and comparison

AssignmentAddressToInteger

Best practice
Medium

Assigning a pointer to an integer is not portable.

assignmentInAssert

Best practice
High

Assert statement modifies variable

AssignmentIntegerToAddress

Security
Medium

Assigning an integer to a pointer is not portable.

autoVariables

Safety
Critical

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

autovarInvalidDeallocation

Safety
Critical

Deallocation of an global variable results in undefined behaviour.

badBitmaskCheck

Error prone
High

Bad usage of bitmap operator

bufferAccessOutOfBounds

Safety
Critical

Buffer is accessed out of bounds: Ltrans[temp].addr

CastAddressToIntegerAtReturn

Safety
Medium

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

CastIntegerToAddressAtReturn

Best practice
Medium

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

catchExceptionByValue

Code style
Minor

Exception should be caught by reference.

charLiteralWithCharPtrCompare

Safety
High

Char literal compared with pointer.

checkCastIntToCharAndBack

Error prone
High

Storing getchar() return value in char variable and then comparing with EOF.

clarifyCalculation

Code style
Minor

Clarify calculation precedence for '+' and '?'.

clarifyCondition

Code style
Minor

Suspicious condition (bitwise operator + comparison)

clarifyStatement

Error prone
High

Misuse of ++ operator

class_X_Y

Error prone
Minor

Code not handled

compareBoolExpressionWithInt

Best practice
High

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

comparePointers

Safety
Critical

Subtracting pointers that point to different objects

comparisonError

Code style
Minor

Detect conditions that are always true

comparisonOfBoolWithInvalidComparator

Error prone
High

Comparison of a boolean value using relational operator (e.g. < ,>, etc)

ConfigurationNotChecked

Best practice
Minor

Skipping configuration 'RLIMIT\_AS;RLIMIT\_CPU;RLIMIT\_DATA;RLIMIT\_NPROC;RLIMIT\_VMEM' since the value of 'RLIMIT\_NPROC' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.

constArgument

Code style
Minor

Argument 'false&&static\_cast<bool>(!!(desc.version()==100))' to function isTrue is always 0

constParameter

Design
Minor

Parameter can be declared with const

constParameterCallback

Design
Minor

Parameter can be declared with const.

constStatement

Best practice
High

Detect unused variables

constVariable

Code style
Minor

Detect variables that could be const

containerOutOfBounds

Safety
High

Access container out of bounds

containerOutOfBoundsIndexExpression

Safety
Critical

Out of bounds access of variable

copyCtorPointerCopying

Design
High

Value of pointer 'count'

coutCerrMisusage

Error prone
Critical

Invalid usage of output stream: '<< std::cout'.

cstyleCast

Code style
Minor

C-style pointer casting

ctuArrayIndex

Safety
Critical

Detect array access out of bounds

ctunullpointer

Safety
Critical

Null pointer dereference: base

ctuPointerArith

Safety
Critical

Pointer arithmetic overflow

ctuuninitvar

Safety
Critical

Using argument that is uninitialized

danglingLifetime

Safety
Critical

Non-local variable use pointer to local variable

danglingTemporaryLifetime

Safety
Critical

Using object to temporary.

danglingTempReference

Safety
Critical

Using reference to dangling temporary.

deallocret

Safety
Critical

Returning/dereferencing value after it is deallocated / released

deallocuse

Safety
Critical

Dereferencing variable after it is deallocated / released

derefInvalidIterator

Error prone
Critical

Possible dereference of an invalid iterator

derefInvalidIteratorRedundantCheck

Best practice
High

Condition is redundant or value is derefenced

doubleFree

Safety
Critical

Memory freed twice

duplicateAssignExpression

Code style
Minor

Duplicate assign expression

duplicateBreak

Code style
Minor

Consecutive return

duplicateCondition

Code style
Minor

Detect duplicate conditions

duplicateConditionalAssign

Code style
Minor

Duplicate conditions

duplicateExpression

Code style
Minor

Duplicate expressions

duplicateExpressionTernary

Code style
Minor

Duplicate Ternary operator

duplicateValueTernary

Code style
Minor

Duplicate ternary value

duplInheritedMember

Design
High

Duplicated inherited member

eraseDereference

Error prone
Critical

Value used after being erased

exceptRethrowCopy

Best practice
Minor

Rethrowing exception in an exception

exceptThrowInDestructor

Best practice
High

Catching exception in destructor

fflushOnInputStream

Error prone
Medium

fflush() called on input stream may result in undefined behaviour on non-linux systems

floatConversionOverflow

Safety
Critical

Float conversation overflow

funcArgOrderDifferent

Best practice
High

Function not called with the right arguments

getsCalled

Best practice
High

Obsolute function gets() called

hidingInheritedPublic

Design
Minor

Virtual function is a public in a base class and became not-public in derived. It's violate a substitutability a principle in OOP.

identicalConditionAfterEarlyExit

Best practice
High

Identical condition and return expression

identicalInnerCondition

Best practice
High

Identical inner 'return' condition is always true.

ignoredReturnValue

Best practice
High

Return value not used

incorrectCharBooleanError

Error prone
High

Conversion of char literal to bool always evaluates to true.

incorrectLogicOperator

Best practice
High

Logical conjunction always evaluates to false

incorrectStringBooleanError

Error prone
High

Incorrect string boolean operator

integerOverflow

Safety
Critical

Integer overflow

integerOverflowCond

Best practice
High

Integer overflow with condition

invalidContainer

Error prone
Critical

Invalid container

invalidContainerLoop

Safety
Critical

Calling 'erase' while iterating the container is invalid.

invalidFunctionArg

Safety
Critical

Invalid function argument

invalidFunctionArgBool

Security
Critical

Invalid boolean argument

invalidFunctionArgStr

Safety
Critical

Invalid string argument

invalidLengthModifierError

Best practice
High

Format string conversion error

invalidLifetime

Safety
Critical

Invalid use of scope/variable lifetime

invalidPointerCast

Best practice
Medium

Invalid pointer cast

invalidPrintfArgType_float

Best practice
High

Invalid formatter for float

invalidPrintfArgType_n

Safety
High

Invalid formatter for int

invalidPrintfArgType_p

Safety
High

Invalid formatter for signed int

invalidPrintfArgType_s

Safety
High

Invalid formatter for string

invalidPrintfArgType_sint

Best practice
High

Invalid formatter for signed long long

invalidPrintfArgType_uint

Best practice
High

Invalid formatter for unsigned int

invalidscanf

Best practice
High

Invalid scanf

invalidScanfArgType_float

Safety
High

Invalid scanf for float

invalidScanfArgType_int

Best practice
High

Invalid scanf for int

invalidScanfArgType_s

Safety
High

Invalid scanf for string

invalidScanfFormatWidth

Safety
Critical

scanf call overwrite the memory allocated for the string

invalidTestForOverflow

Best practice
High

Invalid test for overflow

IOWithoutPositioning

Error prone
Critical

I/O operations without positioning

iterators3

Safety
Critical

Same iterator is used with different scopes

knownArgument

Best practice
Minor

Argument value is always known, could use a const

knownConditionTrueFalse

Code style
Minor

Condition value is always known

knownEmptyContainer

Error prone
Minor

Container is always empty

knownEmptyContainerLoop

Performance
Minor

Iterating over a container that is always empty.

leakNoVarFunctionCall

Best practice
Critical

Allocation failed

leakReturnValNotUsed

Best practice
Critical

return value of function not stored

literalWithCharPtrCompare

Best practice
High

Direct string comparison. Compare with strcmp() instead

localMutex

Safety
High

The lock is ineffective because the mutex is locked at the same scope as the mutex itself.

memleak

Safety
Critical

Memory leak: table.array

memleakOnRealloc

Safety
Critical

Common realloc mistake: value nulled but not freed upon failure

memsetClassFloat

Safety
Medium

Using memset() on union which contains a floating point number.

memsetValueOutOfRange

Security
High

Invalid memset assignment

memsetZeroBytes

Error prone
High

memset() called to fill 0 bytes.

mismatchAllocDealloc

Design
Critical

Mismatching allocation and deallocation

mismatchingContainerExpression

Best practice
High

Iterators to containers from different expressions

missingOverride

Code style
Minor

Function overrides a function in a base class but is not marked with a 'override' specifier.

moduloofone

Safety
Minor

Modulo of one is always equal to zero

multiCondition

Code style
Minor

Expression is always false because 'else if' condition matches previous condition

nanInArithmeticExpression

Best practice
Minor

Using NaN/Inf in a computation.

negativeContainerIndex

Safety
High

Negative container index

negativeIndex

Best practice
High

Negative index access

noConstructor

Code style
Minor

Class does not have a constructor although it has private member variables.

noCopyConstructor

Best practice
High

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

noDestructor

Best practice
Medium

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

noExplicitConstructor

Code style
Minor

Class has a constructor with 1 argument that is not explicit.

noOperatorEq

Best practice
High

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

nullPointer

Safety
Critical

Possible null pointer dereference

nullPointerArithmetic

Safety
Critical

Overflow in pointer arithmetic

nullPointerArithmeticRedundantCheck

Best practice
High

Either the condition is redundant or there is overflow in pointer subtraction.

nullPointerRedundantCheck

Best practice
High

Either the condition is redundant or there is possible null pointer dereference

objectIndex

Best practice
High

The address of local variable might be accessed at non-zero index.

operatorEq

Best practice
Minor

Invalid equal operator

operatorEqMissingReturnStatement

Safety
Critical

No 'return' statement in non-void function causes undefined behavior.

operatorEqRetRefThis

Best practice
Minor

operator=' should return reference to 'this' instance.

operatorEqToSelf

Best practice
High

operator=' should check for assignment to self to avoid problems with dynamic memory.

operatorEqVarError

Best practice
High

Member variable is not assigned a value

oppositeExpression

Code style
Minor

Opposite expression on both sides of expression

oppositeInnerCondition

Best practice
High

Opposite inner 'return' condition leads to a dead code block.

passedByValue

Performance
Medium

Function parameter should be passed by const reference.

pointerArithBool

Safety
Critical

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

pointerLessThanZero

Safety
Minor

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

pointerOutOfBounds

Best practice
Medium

Undefined behaviour

pointerPositive

Performance
Minor

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

pointerSize

Best practice
High

Size of pointer used instead of size of its data.

postfixOperator

Performance
Medium

Prefer prefix ++/-- operators for non-primitive types.

publicAllocationError

Security
High

Possible leak in public function.

readWriteOnlyFile

Safety
Critical

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

redundantAssignInSwitch

Best practice
High

Variable is reassigned a value before the old one has been used

redundantAssignment

Code style
Minor

Variable is reassigned a value before the old one has been used.

redundantCondition

Code style
Minor

Redundant condition

redundantIfRemove

Safety
Minor

Redundant checking of STL container element existence before removing it.

redundantInitialization

Error prone
Minor

Redundant initialization. The initialized value is overwritten before it is read.

redundantPointerOp

Code style
Minor

Redundant pointer operation on 'CB' - it's already a pointer.

resourceLeak

Safety
Critical

Resource leak

returnDanglingLifetime

Safety
Critical

Returning pointer to local variable that will be invalid when returning.

returnNonBoolInBooleanFunction

Safety
Minor

Non-boolean value returned from function returning bool

returnReference

Safety
Critical

Reference to local variable returned.

returnTempReference

Security
Critical

Reference to temporary returned.

sameIteratorExpression

Best practice
Minor

Same iterators expression are used for algorithm.

seekOnAppendedFile

Best practice
High

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

selfAssignment

Best practice
High

Redundant assignment of variable to itself.

selfInitialization

Security
Critical

Member variable is initialized by itself.

shadowArgument

Design
Minor

Local variable shadows outer argument

shadowFunction

Code style
Minor

Local variable shadows outer function

shadowVar

Code style
Minor

Local variable shadows outer variable

shadowVariable

Design
Minor

Local variable shadows outer variable

shiftNegative

Safety
Critical

Shifting by a negative value is undefined behaviour

shiftNegativeLHS

Best practice
Medium

Shifting a negative value is technically undefined behaviour

shiftTooManyBits

Safety
Critical

Shifting 64-bit value by 64 bits is undefined behaviour.

shiftTooManyBitsSigned

Safety
Critical

Shifting signed 32-bit value by 31 bits is implementation-defined behaviour.

signConversion

Best practice
High

Expression can have a negative value. That is converted to an unsigned value and used in an unsigned calculation.

signConversionCond

Security
High

Conversion between unsigned and signed values

sizeofCalculation

Best practice
High

Calculation inside sizeof().

sizeofDivisionMemfunc

Best practice
High

Division by result of sizeof(). memset() expects a size in bytes

sizeofFunctionCall

Error prone
High

Found function call inside sizeof().

sizeofVoid

Error prone
Medium

Behaviour of 'sizeof(void)' is not covered by the ISO C standard.

sizeofwithnumericparameter

Safety
High

Suspicious usage of 'sizeof' with a numeric constant as parameter.

sizeofwithsilentarraypointer

Error prone
High

Using 'sizeof' on array given as function argument returns size of a pointer.

sprintfOverlappingData

Safety
Critical

Undefined behavior: Variable is used as parameter and destination in sprintf().

staticStringCompare

Best practice
High

Unnecessary comparison of static strings.

stlcstr

Safety
Critical

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

stlcstrParam

Performance
Medium

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

stlcstrReturn

Performance
Medium

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

stlFindInsert

Performance
Medium

Searching before insertion is not necessary.

stlIfFind

Error prone
High

Suspicious condition. The result of find() is an iterator

stlIfStrFind

Performance
Medium

Inefficient usage of string::find() in condition; string::starts_with() could be faster.

StlMissingComparison

Safety
High

Missing bounds check for extra iterator increment in loop.

stlOutOfBounds

Safety
Critical

Out of bounds acess to a container

stringLiteralWrite

Code style
Critical

Modifying string literal directly or indirectly is undefined behaviour.

strPlusChar

Safety
Critical

Unusual pointer arithmetic.

templateRecursion

Design
Minor

Template recursion threshold reached

thisSubtraction

Safety
High

Suspicious pointer subtraction.

throwInNoexceptFunction

Safety
Critical

Exception thrown in function declared not to throw exceptions.

truncLongCastAssignment

Safety
Minor

int result is assigned to long variable. If the variable is long to avoid loss of information

truncLongCastReturn

Error prone
Minor

int result is returned as long value. If the return value is long to avoid loss of information

unassignedVariable

Code style
Minor

Detect variables that are not assigned (e.g. dead code)

uninitdata

Security
Critical

Memory is allocated but not initialized

uninitMemberVar

Best practice
High

Member variable not initialized in the constructor.

uninitMemberVarPrivate

Best practice
High

Member private variable is not initialized in the constructor.

uninitStructMember

Security
Critical

Uninitialized struct member

uninitvar

Safety
Critical

Uninitialized variable

unpreciseMathCall

Unknown
Minor

Expression can be replaced to avoid loss of precision.

unreachableCode

Code style
Minor

Statements following return ; dead code

unsafeClassCanLeak

Security
Minor

Class is unsafe

unsafeClassDivZero

Code style
Minor

Public interface is not safe.

unsignedLessThanZero

Code style
Minor

Checking if unsigned expression is less than zero.

unsignedPositive

Code style
Minor

Unsigned expression can't be negative so it is unnecessary to test it.

unusedAllocatedMemory

Code style
Minor

Variable is allocated memory that is never used.

unusedLabel

Code style
Minor

Label is not used.

unusedLabelConfiguration

Design
Minor

Label is not used, a pre-processor configuration prevents it to be shown.

unusedLabelSwitch

Design
High

Label is not used.

unusedLabelSwitchConfiguration

Design
High

Unused label in switch

unusedPrivateFunction

Code style
Minor

Unused private function

unusedScopedObject

Best practice
Minor

Instance of object is destroyed immediately.

unusedStructMember

Code style
Minor

struct member is never used.

unusedVariable

Code style
Minor

Unused variable

useClosedFile

Safety
Critical

Used file that is not opened.

useInitializationList

Performance
Medium

Variable is assigned in constructor body. Consider performing initialization in initialization list.

uselessAssignmentArg

Code style
Minor

Assignment of function parameter has no effect outside the function.

uselessAssignmentPtrArg

Best practice
High

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

uselessCallsEmpty

Best practice
High

Ineffective call of function 'empty()'. Call 'clear()' instead.

uselessCallsRemove

Error prone
High

Return value ignored. Elements remain in container.

uselessCallsSubstr

Performance
Medium

Ineffective call of function 'substr' because it returns a copy of the object. Use operator= instead.

useStlAlgorithm

Code style
Minor

Consider using std::generate algorithm instead of a raw loop.

va_end_missing

Safety
Critical

va\_list 'argument\_list' was opened but not closed by va\_end().

va_list_usedBeforeStarted

Safety
Critical

va\_list 'cpy' used before va\_start() was called.

va_start_subsequentCalls

Safety
Critical

va\_start() or va\_copy() called subsequently on 'argptr' without va\_end() in between.

varFuncNullUB

Best practice
Medium

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

virtualCallInConstructor

Best practice
High

Dynamic binding is not used.

virtualDestructor

Design
Critical

Class which is inherited does not have a virtual destructor.

writeReadOnlyFile

Error prone
Critical

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

wrongPrintfScanfArgNum

Safety
Critical

mismatch printf parameters

wrongPrintfScanfParameterPositionError

Error prone
High

printf: invalid parameter position

zerodiv

Safety
Critical

Division by zero.

zerodivcond

Safety
High

Either the condition is redundant or there is division by zero

pointerOutOfBoundsCond

Security
High

Undefined behaviour, when 'len' is 4 the pointer arithmetic 'cmd+len' is out of bounds

mismatchingBitAnd

Best practice
High

Mismatching bitmasks.

comparisonOfBoolWithBoolError

Error prone
Medium

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

ctuOneDefinitionRuleViolation

Design
High

The one definition rule is violated, different classes/structs have the same name.

uninitDerivedMemberVar

Safety
High

Member variable not initialized in constructor

legacyUninitvar

Best practice
Minor

Uninitialized variable

missingReturn

Safety
Critical

Missing return statement

returnStdMoveLocal

Best practice
High

Using std::move for returning object by-value from function will affect copy elision optimization

Learn more

overlappingWriteUnion

Safety
High

Overlapping read/write of union is undefined behavior

argumentSize

Security
High

Buffer is too small

nonStandardCharLiteral

Error prone
Minor

Non-standard character literal

mismatchingContainers

Safety
High

Iterators of different containers are used together.

rethrowNoCurrentException

Error prone
Medium

Rethrowing current exception

operatorEqShouldBeLeftUnimplemented

Design
High

operator should either return reference to 'this' instance or be declared private and left unimplemented.

va_start_wrongParameter

Error prone
High

Wrong parameter for va_start()

pureVirtualCall

Error prone
Medium

Call of pure virtual function in constructor.