facebook pixelCodiga Analysis C / C++ 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
Error

Access of forwarded variable

accessMoved

Best practice
Error

Access of moved variable.

allocaCalled

Best practice
Error

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

arithOperationsOnVoidPointer

Best practice
Warning

Avoid arithmetic operation on void pointers

arrayIndexOutOfBounds

Safety
Critical

Array accessed out of bounds

arrayIndexOutOfBoundsCond

Best practice
Error

Array access out of bounds with a conditions

arrayIndexThenCheck

Code style
Informational

Access array beyond boundaries

asctime_sCalled

Best practice
Error

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

asctimeCalled

Code style
Informational

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

assertWithSideEffect

Best practice
Error

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

assignBoolToFloat

Safety
Informational

Boolean value assigned to floating point variable.

assignBoolToPointer

Security
Critical

Boolean value assigned to pointer.

assignIfError

Error prone
Informational

Mismatching assignment and comparison

AssignmentAddressToInteger

Best practice
Warning

Assigning a pointer to an integer is not portable.

assignmentInAssert

Best practice
Error

Assert statement modifies variable

AssignmentIntegerToAddress

Security
Warning

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
Error

Bad usage of bitmap operator

bufferAccessOutOfBounds

Safety
Critical

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

CastAddressToIntegerAtReturn

Safety
Warning

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

CastIntegerToAddressAtReturn

Best practice
Warning

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

catchExceptionByValue

Code style
Informational

Exception should be caught by reference.

charLiteralWithCharPtrCompare

Safety
Error

Char literal compared with pointer.

checkCastIntToCharAndBack

Error prone
Error

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

clarifyCalculation

Code style
Informational

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

clarifyCondition

Code style
Informational

Suspicious condition (bitwise operator + comparison)

clarifyStatement

Error prone
Error

Misuse of ++ operator

class_X_Y

Error prone
Informational

Code not handled

compareBoolExpressionWithInt

Best practice
Error

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
Informational

Detect conditions that are always true

comparisonOfBoolWithInvalidComparator

Error prone
Error

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

ConfigurationNotChecked

Best practice
Informational

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
Informational

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

constParameter

Design
Informational

Parameter can be declared with const

constParameterCallback

Design
Informational

Parameter can be declared with const.

constStatement

Best practice
Error

Detect unused variables

constVariable

Code style
Informational

Detect variables that could be const

containerOutOfBounds

Safety
Error

Access container out of bounds

containerOutOfBoundsIndexExpression

Safety
Critical

Out of bounds access of variable

copyCtorPointerCopying

Design
Error

Value of pointer 'count'

coutCerrMisusage

Error prone
Critical

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

cstyleCast

Code style
Informational

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
Error

Condition is redundant or value is derefenced

doubleFree

Safety
Critical

Memory freed twice

duplicateAssignExpression

Code style
Informational

Duplicate assign expression

duplicateBreak

Code style
Informational

Consecutive return

duplicateCondition

Code style
Informational

Detect duplicate conditions

duplicateConditionalAssign

Code style
Informational

Duplicate conditions

duplicateExpression

Code style
Informational

Duplicate expressions

duplicateExpressionTernary

Code style
Informational

Duplicate Ternary operator

duplicateValueTernary

Code style
Informational

Duplicate ternary value

duplInheritedMember

Design
Error

Duplicated inherited member

eraseDereference

Error prone
Critical

Value used after being erased

exceptRethrowCopy

Best practice
Informational

Rethrowing exception in an exception

exceptThrowInDestructor

Best practice
Error

Catching exception in destructor

fflushOnInputStream

Error prone
Warning

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

floatConversionOverflow

Safety
Critical

Float conversation overflow

funcArgOrderDifferent

Best practice
Error

Function not called with the right arguments

getsCalled

Best practice
Error

Obsolute function gets() called

hidingInheritedPublic

Design
Informational

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
Error

Identical condition and return expression

identicalInnerCondition

Best practice
Error

Identical inner 'return' condition is always true.

ignoredReturnValue

Best practice
Error

Return value not used

incorrectCharBooleanError

Error prone
Error

Conversion of char literal to bool always evaluates to true.

incorrectLogicOperator

Best practice
Error

Logical conjunction always evaluates to false

incorrectStringBooleanError

Error prone
Error

Incorrect string boolean operator

integerOverflow

Safety
Critical

Integer overflow

integerOverflowCond

Best practice
Error

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
Error

Format string conversion error

invalidLifetime

Safety
Critical

Invalid use of scope/variable lifetime

invalidPointerCast

Best practice
Warning

Invalid pointer cast

invalidPrintfArgType_float

Best practice
Error

Invalid formatter for float

invalidPrintfArgType_n

Safety
Error

Invalid formatter for int

invalidPrintfArgType_p

Safety
Error

Invalid formatter for signed int

invalidPrintfArgType_s

Safety
Error

Invalid formatter for string

invalidPrintfArgType_sint

Best practice
Error

Invalid formatter for signed long long

invalidPrintfArgType_uint

Best practice
Error

Invalid formatter for unsigned int

invalidscanf

Best practice
Error

Invalid scanf

invalidScanfArgType_float

Safety
Error

Invalid scanf for float

invalidScanfArgType_int

Best practice
Error

Invalid scanf for int

invalidScanfArgType_s

Safety
Error

Invalid scanf for string

invalidScanfFormatWidth

Safety
Critical

scanf call overwrite the memory allocated for the string

invalidTestForOverflow

Best practice
Error

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
Informational

Argument value is always known, could use a const

knownConditionTrueFalse

Code style
Informational

Condition value is always known

knownEmptyContainer

Error prone
Informational

Container is always empty

knownEmptyContainerLoop

Performance
Informational

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
Error

Direct string comparison. Compare with strcmp() instead

localMutex

Safety
Error

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
Warning

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

memsetValueOutOfRange

Security
Error

Invalid memset assignment

memsetZeroBytes

Error prone
Error

memset() called to fill 0 bytes.

mismatchAllocDealloc

Design
Critical

Mismatching allocation and deallocation

mismatchingContainerExpression

Best practice
Error

Iterators to containers from different expressions

missingOverride

Code style
Informational

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

moduloofone

Safety
Informational

Modulo of one is always equal to zero

multiCondition

Code style
Informational

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

nanInArithmeticExpression

Best practice
Informational

Using NaN/Inf in a computation.

negativeContainerIndex

Safety
Error

Negative container index

negativeIndex

Best practice
Error

Negative index access

noConstructor

Code style
Informational

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

noCopyConstructor

Best practice
Error

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

noDestructor

Best practice
Warning

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

noExplicitConstructor

Code style
Informational

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

noOperatorEq

Best practice
Error

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
Error

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

nullPointerRedundantCheck

Best practice
Error

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

objectIndex

Best practice
Error

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

operatorEq

Best practice
Informational

Invalid equal operator

operatorEqMissingReturnStatement

Safety
Critical

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

operatorEqRetRefThis

Best practice
Informational

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

operatorEqToSelf

Best practice
Error

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

operatorEqVarError

Best practice
Error

Member variable is not assigned a value

oppositeExpression

Code style
Informational

Opposite expression on both sides of expression

oppositeInnerCondition

Best practice
Error

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

passedByValue

Performance
Warning

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
Informational

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

pointerOutOfBounds

Best practice
Warning

Undefined behaviour

pointerPositive

Performance
Informational

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

pointerSize

Best practice
Error

Size of pointer used instead of size of its data.

postfixOperator

Performance
Warning

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

publicAllocationError

Security
Error

Possible leak in public function.

readWriteOnlyFile

Safety
Critical

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

redundantAssignInSwitch

Best practice
Error

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

redundantAssignment

Code style
Informational

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

redundantCondition

Code style
Informational

Redundant condition

redundantIfRemove

Safety
Informational

Redundant checking of STL container element existence before removing it.

redundantInitialization

Error prone
Informational

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

redundantPointerOp

Code style
Informational

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
Informational

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
Informational

Same iterators expression are used for algorithm.

seekOnAppendedFile

Best practice
Error

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

selfAssignment

Best practice
Error

Redundant assignment of variable to itself.

selfInitialization

Security
Critical

Member variable is initialized by itself.

shadowArgument

Design
Informational

Local variable shadows outer argument

shadowFunction

Code style
Informational

Local variable shadows outer function

shadowVar

Code style
Informational

Local variable shadows outer variable

shadowVariable

Design
Informational

Local variable shadows outer variable

shiftNegative

Safety
Critical

Shifting by a negative value is undefined behaviour

shiftNegativeLHS

Best practice
Warning

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
Error

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

signConversionCond

Security
Error

Conversion between unsigned and signed values

sizeofCalculation

Best practice
Error

Calculation inside sizeof().

sizeofDivisionMemfunc

Best practice
Error

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

sizeofFunctionCall

Error prone
Error

Found function call inside sizeof().

sizeofVoid

Error prone
Warning

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

sizeofwithnumericparameter

Safety
Error

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

sizeofwithsilentarraypointer

Error prone
Error

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
Error

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
Warning

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

stlcstrReturn

Performance
Warning

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

stlFindInsert

Performance
Warning

Searching before insertion is not necessary.

stlIfFind

Error prone
Error

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

stlIfStrFind

Performance
Warning

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

StlMissingComparison

Safety
Error

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
Informational

Template recursion threshold reached

thisSubtraction

Safety
Error

Suspicious pointer subtraction.

throwInNoexceptFunction

Safety
Critical

Exception thrown in function declared not to throw exceptions.

truncLongCastAssignment

Safety
Informational

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

truncLongCastReturn

Error prone
Informational

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

unassignedVariable

Code style
Informational

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

uninitdata

Security
Critical

Memory is allocated but not initialized

uninitMemberVar

Best practice
Error

Member variable not initialized in the constructor.

uninitMemberVarPrivate

Best practice
Error

Member private variable is not initialized in the constructor.

uninitStructMember

Security
Critical

Uninitialized struct member

uninitvar

Safety
Critical

Uninitialized variable

unpreciseMathCall

Unknown
Informational

Expression can be replaced to avoid loss of precision.

unreachableCode

Code style
Informational

Statements following return ; dead code

unsafeClassCanLeak

Security
Informational

Class is unsafe

unsafeClassDivZero

Code style
Informational

Public interface is not safe.

unsignedLessThanZero

Code style
Informational

Checking if unsigned expression is less than zero.

unsignedPositive

Code style
Informational

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

unusedAllocatedMemory

Code style
Informational

Variable is allocated memory that is never used.

unusedLabel

Code style
Informational

Label is not used.

unusedLabelConfiguration

Design
Informational

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

unusedLabelSwitch

Design
Error

Label is not used.

unusedLabelSwitchConfiguration

Design
Error

Unused label in switch

unusedPrivateFunction

Code style
Informational

Unused private function

unusedScopedObject

Best practice
Informational

Instance of object is destroyed immediately.

unusedStructMember

Code style
Informational

struct member is never used.

unusedVariable

Code style
Informational

Unused variable

useClosedFile

Safety
Critical

Used file that is not opened.

useInitializationList

Performance
Warning

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

uselessAssignmentArg

Code style
Informational

Assignment of function parameter has no effect outside the function.

uselessAssignmentPtrArg

Best practice
Error

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

uselessCallsEmpty

Best practice
Error

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

uselessCallsRemove

Error prone
Error

Return value ignored. Elements remain in container.

uselessCallsSubstr

Performance
Warning

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

useStlAlgorithm

Code style
Informational

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
Warning

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

virtualCallInConstructor

Best practice
Error

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
Error

printf: invalid parameter position

zerodiv

Safety
Critical

Division by zero.

zerodivcond

Safety
Error

Either the condition is redundant or there is division by zero

pointerOutOfBoundsCond

Security
Error

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

mismatchingBitAnd

Best practice
Error

Mismatching bitmasks.

comparisonOfBoolWithBoolError

Error prone
Warning

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

ctuOneDefinitionRuleViolation

Design
Error

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

uninitDerivedMemberVar

Safety
Error

Member variable not initialized in constructor

legacyUninitvar

Best practice
Informational

Uninitialized variable

missingReturn

Safety
Critical

Missing return statement

returnStdMoveLocal

Best practice
Error

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

Learn more

overlappingWriteUnion

Safety
Error

Overlapping read/write of union is undefined behavior

argumentSize

Security
Error

Buffer is too small

nonStandardCharLiteral

Error prone
Informational

Non-standard character literal

mismatchingContainers

Safety
Error

Iterators of different containers are used together.

rethrowNoCurrentException

Error prone
Warning

Rethrowing current exception

operatorEqShouldBeLeftUnimplemented

Design
Error

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

va_start_wrongParameter

Error prone
Error

Wrong parameter for va_start()

pureVirtualCall

Error prone
Warning

Call of pure virtual function in constructor.