Main Content

MISRA C:2004 and MISRA AC AGC Coding Rules

Supported MISRA C:2004 and MISRA AC AGC Rules

The following tables list MISRA C™:2004 coding rules that the Polyspace® coding rules checker supports. Details regarding how the software checks individual rules and any limitations on the scope of checking are described in the “Polyspace Specification” column.

Note

The Polyspace coding rules checker:

  • Supports MISRA-C:2004 Technical Corrigendum 1 for rules 4.1, 5.1, 5.3, 6.1, 6.3, 7.1, 9.2, 10.5, 12.6, 13.5, and 15.0.

  • Checks rules specified by MISRA AC AGC Guidelines for the Application of MISRA-C:2004 in the Context of Automatic Code Generation.

The software reports most violations during the compile phase of an analysis. However, the software detects violations of rules 9.1 (Non-initialized variable), 12.11 (one of the overflow checks) using -scalar-overflows-checks signed-and-unsigned), 13.7 (dead code), 14.1 (dead code), 16.2 and 21.1 during code analysis, and reports these violations as run-time errors.

Note

Some violations of rules 13.7 and 14.1 are reported during the compile phase of analysis.

Troubleshooting

If you expect a rule violation but do not see it, check out Diagnose Why Coding Standard Violations Do Not Appear as Expected.

List of Supported Coding Rules

Environment

N.MISRA™ DefinitionMessages in report filePolyspace Implementation
1.1All code shall conform to ISO® 9899:1990 “Programming languages - C”, amended and corrected by ISO/IEC 9899/COR1:1995, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996.

The text All code shall conform to ISO 9899:1990 Programming languages C, amended and corrected by ISO/IEC 9899/COR1:1995, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996 precedes each of the following messages:

  • ANSI® C does not allow ‘#include_next'

  • ANSI C does not allow macros with variable arguments list 

  • ANSI C does not allow ‘#assert’ 

  • ANSI C does not allow '#unassert' 

  • ANSI C does not allow testing assertions

  • ANSI C does not allow '#ident'

  • ANSI C does not allow '#sccs'

  • text following '#else' violates ANSI standard.

  • text following '#endif' violates ANSI standard.

  • text following '#else' or '#endif' violates ANSI standard.

  • ANSI C90 forbids 'long long int' type.

  • ANSI C90 forbids 'long double' type.

  • ANSI C90 forbids long long integer constants.

  • Keyword 'inline' should not be used.

  • Array of zero size should not be used.

  • Integer constant does not fit within unsigned long int.

  • Integer constant does not fit within long int.

  • Too many nesting levels of #includes: N1. The limit is N0.

  • Too many macro definitions: N1. The limit is N0.

  • Too many nesting levels for control flow: N1. The limit is N0.

  • Too many enumeration constants: N1. The limit is N0.

All the supported extensions lead to a violation of this MISRA rule. Standard compilation error messages do not lead to a violation of this MISRA rule and remain unchanged.

Language Extensions

N.MISRA DefinitionMessages in report filePolyspace Implementation
2.1Assembly language shall be encapsulated and isolated.Assembly language shall be encapsulated and isolated.

No warnings if code is encapsulated in the following:

  • asm functions or asm pragma

  • Macros

2.2Source code shall only use /* */ style commentsC++ comments shall not be used.

C++ comments are handled as comments but lead to a violation of this MISRA rule

Note: This rule cannot be annotated in the source code.

2.3The character sequence /* shall not be used within a commentThe character sequence /* shall not appear within a comment.

This rule violation is also raised when the character sequence /* inside a C++ comment.

Note: This rule cannot be annotated in the source code.

2.4Sections of code should not be "commented out"Sections of code should not be "commented out"

The checker uses internal heuristics to detect commented out code. For instance, characters such as #, ;, { or } indicate comments that might potentially contain code. These comments are then evaluated against other metrics to determine the likelihood of code masquerading as comment. For instance, several successive words without a symbol in between reduces this likelihood.

The checker does not flag the following comments even if they contain code:

  • Doxygen comments beginning with /** or /*!.

  • Comments that repeat the same symbol several times, for instance, the symbol = here:

    /* =====================================
     * A comment
     * =====================================*/

  • Comments on the first line of a file.

  • Comments that mix the C style (/* */) and C++ style (//).

The checker considers that these comments are meant for documentation purposes or entered deliberately with some forethought.

Documentation

RuleMISRA DefinitionMessages in report filePolyspace Implementation
3.4

All uses of the #pragma directive shall be documented and explained.

All uses of the #pragma directive shall be documented and explained.To check this rule, you must list the pragmas that are allowed in source files by using the option Allowed pragmas (-allowed-pragmas). If Polyspace finds a pragma not in the allowed pragma list, a violation is raised.

Character Sets

N.MISRA DefinitionMessages in report filePolyspace Implementation
4.1Only those escape sequences which are defined in the ISO C standard shall be used.\<character> is not an ISO C escape sequence Only those escape sequences which are defined in the ISO C standard shall be used. 
4.2Trigraphs shall not be used.Trigraphs shall not be used.Trigraphs are handled and converted to the equivalent character but lead to a violation of the MISRA rule

Identifiers

N.MISRA DefinitionMessages in report filePolyspace Implementation
5.1Identifiers (internal and external) shall not rely on the significance of more than 31 charactersIdentifier 'XX' should not rely on the significance of more than 31 characters.

All identifiers (global, static and local) are checked.

For easier review, the rule checker shows all identifiers that have the same first 31 characters as one rule violation. You can see all instances of conflicting identifier names in the event history of that rule violation.

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

5.2

Identifiers in an inner scope shall not use the same name as an identifier in an outer scope, and therefore hide that identifier.

  • Local declaration of XX is hiding another identifier.

  • Declaration of parameter XX is hiding another identifier.

Assumes that rule 8.1 is not violated.

5.3

A typedef name shall be a unique identifier

{typedef name}'%s' should not be reused. (already used as {typedef name} at %s:%d)

Warning when a typedef name is reused as another identifier name.

5.4

A tag name shall be a unique identifier

{tag name}'%s' should not be reused. (already used as {tag name} at %s:%d)

Warning when a tag name is reused as another identifier name

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

5.5

No object or function identifier with a static storage duration should be reused.

{static identifier/parameter name}’%s’ should not be reused. (already used as {static identifier/parameter name} with static storage duration at %s:%d)

Warning when a static name is reused as another identifier name

5.6

No identifier in one name space should have the same spelling as an identifier in another name space, with the exception of structure and union member names.

{member name}'%s' should not be reused. (already used as {member name} at %s:%d)

Warning when an idf in a namespace is reused in another namespace

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

5.7

No identifier name should be reused.

{identifier}'%s' should not be reused. (already used as {identifier} at %s:%d)

No violation reported when:

  • Different functions have parameters with the same name

  • Different functions have local variables with the same name

  • A function has a local variable that has the same name as a parameter of another function

Types

N.MISRA DefinitionMessages in report filePolyspace Implementation

6.1

The plain char type shall be used only for the storage and use of character values

Only permissible operators on plain chars are '=', '==' or '!=' operators, explicit casts to integral types and '?' (for the 2nd and 3rd operands)

Warning when a plain char is used with an operator other than =, ==, !=, explicit casts to integral types, or as the second or third operands of the ? operator.

6.2

Signed and unsigned char type shall be used only for the storage and use of numeric values.
  • Value of type plain char is implicitly converted to signed char.

  • Value of type plain char is implicitly converted to unsigned char.

  • Value of type signed char is implicitly converted to plain char.

  • Value of type unsigned char is implicitly converted to plain char.

Warning if value of type plain char is implicitly converted to value of type signed char or unsigned char.

6.3

typedefs that indicate size and signedness should be used in place of the basic types

typedefs that indicate size and signedness should be used in place of the basic types.

No warning is given in typedef definition.

6.4

Bit fields shall only be defined to be of type unsigned int or signed int.

Bit fields shall only be defined to be of type unsigned int or signed int.

 

6.5

Bit fields of type signed int shall be at least 2 bits long.

Bit fields of type signed int shall be at least 2 bits long.

No warning on anonymous signed int bitfields of width 0  - Extended to all signed bitfields of size <= 1 (if Rule 6.4 is violated).

Constants

N.MISRA DefinitionMessages in report filePolyspace Implementation
7.1Octal constants (other than zero) and octal escape sequences shall not be used.
  • Octal constants other than zero and octal escape sequences shall not be used.

  • Octal constants (other than zero) should not be used.

  • Octal escape sequences should not be used.

 

Declarations and Definitions

N.MISRA DefinitionMessages in report filePolyspace Implementation
8.1

Functions shall have prototype declarations and the prototype shall be visible at both the function definition and call.

  • Function XX has no complete prototype visible at call.

  • Function XX has no prototype visible at definition.

Prototype visible at call must be complete.

8.2

Whenever an object or function is declared or defined, its type shall be explicitly stated

Whenever an object or function is declared or defined, its type shall be explicitly stated.

 
8.3For each function parameter the type given in the declaration and definition shall be identical, and the return types shall also be identical.Definition of function 'XX' incompatible with its declaration.Assumes that rule 8.1 is not violated. The rule is restricted to compatible types. Can be turned to Off
8.4

If objects or functions are declared more than once their types shall be compatible.

  • If objects or functions are declared more than once their types shall be compatible.

  • Global declaration of 'XX' function has incompatible type with its definition.

  • Global declaration of 'XX' variable has incompatible type with its definition.

Violations of this rule might be generated during the link phase.

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

8.5

There shall be no definitions of objects or functions in a header file

  • Object 'XX' should not be defined in a header file.

  • Function 'XX' should not be defined in a header file.

  • Fragment of function should not be defined in a header file.

Tentative definitions are considered as definitions. For objects with file scope, tentative definitions are declarations that:

  • Do not have initializers.

  • Do not have storage class specifiers, or have the static specifier

8.6

Functions shall always be declared at file scope.

Function 'XX' should be declared at file scope.

This rule maps to ISO/IEC TS 17961 ID addrescape.

8.7Objects shall be defined at block scope if they are only accessed from within a single functionObject 'XX' should be declared at block scope.Restricted to static objects.
8.8An external object or function shall be declared in one file and only one fileFunction/Object 'XX' has external declarations in multiple files.

Restricted to explicit extern declarations (tentative definitions are ignored).

Polyspace considers that variables or functions declared extern in a non-header file violate this rule.

8.9

An identifier with external linkage shall have exactly one external definition.

  • Procedure/Global variable XX multiply defined.

  • Forbidden multiple tentative definitions for object XX

  • Global variable has multiple tentative definitions

  • Undefined global variable XX

The checker flags multiple definitions only if the definitions occur in different files.

No warnings appear on predefined symbols.

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

8.10

All declarations and definitions of objects or functions at file scope shall have internal linkage unless external linkage is required

Function/Variable XX should have internal linkage.

Assumes that 8.1 is not violated. No warning if 0 uses.

If your code does not contain a main function and you use options such as Variables to initialize (-main-generator-writes-variables) with value custom to explicitly specify a set of variables to initialize, the checker does not flag those variables. The checker assumes that in a real application, the file containing the main must initialize the variables in addition to any file that currently uses them. Therefore, the variables must be used in more than one translation unit.

This checker is deactivated in a default Polyspace as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

8.11

The static storage class specifier shall be used in definitions and  declarations of objects and functions that have internal linkage

static storage class specifier should be used on internal linkage symbol XX.

 
8.12

When an array is declared with external linkage, its size shall be stated explicitly or defined implicitly by initialization

Size of array 'XX' should be explicitly stated.

 

Initialisation

N.MISRA DefinitionMessages in report filePolyspace Implementation
9.1

All automatic variables shall have been assigned a value before being used.

 

Polyspace reports a violation of this rule if your code contains these issues:

9.2

Braces shall be used to indicate and match the structure in the nonzero initialisation of arrays and structures.

Braces shall be used to indicate and match the structure in the nonzero initialization of arrays and structures.

 
9.3

In an enumerator list, the = construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized.

In an enumerator list, the = construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized.

 

Arithmetic Type Conversion

N.MISRA DefinitionMessages in report filePolyspace Implementation
10.1

The value of an expression of integer type shall not be implicitly converted to a different underlying type if:

  • it is not a conversion to a wider integer type of the same signedness, or

  • the expression is complex, or

  • the expression is not constant and is a function argument, or

  • the expression is not constant and is a return expression

  • Implicit conversion of the expression of underlying type XX to the type XX that is not a wider integer type of the same signedness.

  • Implicit conversion of one of the binary operands whose underlying types are XX and XX

  • Implicit conversion of the binary right hand operand of underlying type  XX to XX that is not an integer type.

  • Implicit conversion of the binary left hand operand of underlying type XX to XX that is not an integer type.

  • Implicit conversion of the binary right hand operand of underlying type XX to XX that is not a wider integer type of the same signedness or Implicit conversion of the binary ? left hand operand of underlying type XX to XX, but it is a complex expression.

  • Implicit conversion of complex integer expression of underlying type XX to XX.

  • Implicit conversion of non-constant integer expression of underlying type XX in function return whose expected type is XX.

  • Implicit conversion of non-constant integer expression of underlying type XX as argument of function whose corresponding parameter type is XX.

ANSI C base types order (signed char, short, int, long) defines that T2 is wider than T1 if T2 is on the right hand of T1 or T2 = T1. The same interpretation is applied on the unsigned version of base types.

An expression of bool or enum types has int as underlying type.

Plain char may have signed or unsigned underlying type (depending on Polyspace target configuration or option setting).

The underlying type of a simple expression of struct.bitfield is the base type used in the bitfield definition, the bitfield width is not token into account and it assumes that only signed | unsigned int are used for bitfield (Rule 6.4).

No violation reported when:

  • The implicit conversion is a type widening, without change of signedness if integer

  • The expression is an argument expression or a return expression

No violation reported when the following are all true:

  • Implicit conversion applies to a constant expression and is a type widening, with a possible change of signedness if integer

  • The conversion does not change the representation of the constant value or the result of the operation

  • The expression is an argument expression or a return expression or an operand expression of a non-bitwise operator

No violation reported on operations involving pointers.

Conversions of constants are not reported for these cases to avoid flagging too many violations. If the constant can be represented in both the original and converted type, the conversion is less of an issue.

10.2

The value of an expression of floating type shall not be implicitly converted to a different type if

  • it is not a conversion to a wider floating type, or

  • the expression is complex, or

  • the expression is a function argument, or

  • the expression is a return expression

  • Implicit conversion of the expression from XX to XX that is not a wider floating type.

  • Implicit conversion of the binary ? right hand operand from XX to XX, but it is a complex expression.

  • Implicit conversion of the binary ? right hand operand from XX to XX that is not a wider floating type or Implicit conversion of the binary ? left hand operand from XX to XX, but it is a complex expression.

  • Implicit conversion of complex floating expression from XX to XX.

  • Implicit conversion of floating expression of XX type in function return whose expected type is XX.

  • Implicit conversion of floating expression of XX type as argument of function whose corresponding parameter type is XX.

ANSI C base types order (float, double) defines that T2 is wider than T1 if T2 is on the right hand of T1 or T2 = T1.

No violation reported when:

  • The implicit conversion is a type widening

  • The expression is an argument expression or a return expression.

10.3

The value of a complex expression of integer type may only be cast to a type that is narrower and of the same signedness as the underlying type of the expression

Complex expression of underlying type XX may only be cast to narrower integer type of same signedness, however the destination type is XX.

  • The rule checker raises a defect only if the result of a composite expression is cast to a different or wider essential type.

    For instance, in this example, a violation is shown in the first assignment to i but not the second. In the first assignment, a composite expression i+1 is directly cast from a signed to an unsigned type. In the second assignment, the composite expression is first cast to the same type and then the result is cast to a different type.

    typedef int int32_T;
    typedef unsigned char uint8_T; 
    ...
    ...
    int32_T i;
    i = (uint8_T)(i+1); /* Noncompliant */
    i = (uint8_T)((int32_T)(i+1));
     /* Compliant */

  • ANSI C base types order (signed char, short, int, long) defines that T1 is narrower than T2 if T2 is on the right hand of T1 or T1 = T2. The same methodology is applied on the unsigned version of base types.

  • An expression of bool or enum types has int as underlying type.

  • Plain char may have signed or unsigned underlying type (depending on  target configuration or option setting).

  • The underlying type of a simple expression of struct.bitfield is the base type  used in the bitfield definition, the bitfield width is not token into account and  it assumes that only signed, unsigned int are used for bitfield (Rule 6.4).

10.4

The value of a complex expression of float type may only be cast to narrower floating type

Complex expression of XX type may only be cast to narrower floating type, however the destination type is XX.

ANSI C base types order (float, double) defines that T1 is narrower than T2 if T2 is on the right hand of T1 or T2 = T1. 

10.5

If the bitwise operator ~ and << are applied to an operand of underlying type unsigned char or unsigned short, the result shall be immediately cast to the underlying type of the operand

Bitwise [<<|~] is applied to the operand of underlying type [unsigned char|unsigned short], the result shall be immediately cast to the underlying type.

 
10.6

The “U” suffix shall be applied to all constants of unsigned types

No explicit 'U suffix on constants of an unsigned type.

 Warning when the type determined from the value and the base (octal, decimal or hexadecimal) is unsigned and there is no suffix u or U.

For example, when the size of the int and long int data types is 32 bits, the coding rule checker will report a violation of rule 10.6 for the following line:

int a = 2147483648;

There is a difference between decimal and hexadecimal constants when int and long int are not the same size.

Pointer Type Conversion

N.MISRA DefinitionMessages in report filePolyspace Implementation
11.1

Conversion shall not be performed between a pointer to a function and any type other than an integral type

Conversion shall not be performed between a pointer to a function and any type other than an integral type.

Casts and implicit conversions involving a function pointer.

Casts or implicit conversions from NULL or (void*)0 do not give any warning.

11.2

Conversion shall not be performed between a pointer to an object and any type other than an integral type, another pointer to a object type or a pointer to void

Conversion shall not be performed between a pointer to an object and any type other than an integral type, another pointer to a object type or a pointer to void.

There is also a warning on qualifier loss

This rule maps to ISO/IEC TS 17961 ID alignconv.

11.3

A cast should not be performed between a pointer type and an integral type

A cast should not be performed between a pointer type and an integral type.

Exception on zero constant. Extended to all conversions

This rule maps to ISO/IEC TS 17961 ID alignconv.

11.4

A cast should not be performed between a pointer to object type and a different pointer to object type.

A cast should not be performed between a pointer to object type and a different pointer to object type.

 
11.5

A cast shall not be performed that removes any const or volatile qualification from the type addressed by a pointer

A cast shall not be performed that removes any const or volatile qualification from the type addressed by a pointer

Extended to all conversions

Expressions

N.MISRA DefinitionMessages in report filePolyspace Implementation
12.1

Limited dependence should be placed on C's operator precedence rules in expressions

Limited dependence should be placed on C's operator precedence rules in expressions

 
12.2The value of an expression shall be the same under any order of evaluation that the standard permits.
  • The value of 'sym' depends on the order of evaluation.

  • The value of volatile 'sym' depends on the order of evaluation because of multiple accesses.

Rule 12.2 check assumes that no assignment in expressions that yield a Boolean values (rule 13.1).

The expression is a simple expression of symbols. i = i++; is a violation, but tab[2] = tab[2]++; is not a violation.

12.3

The sizeof operator should not be used on expressions that contain side effects.

The sizeof operator should not be used on expressions that contain side effects.

No warning on volatile accesses

12.4

The right hand operand of a logical && or || operator shall not contain side effects.

The right hand operand of a logical && or || operator shall not contain side effects.

No warning on volatile accesses

12.5

The operands of a logical && or || shall be primary-expressions.

  • operand of logical && is not a primary expression

  • operand of logical || is not a primary expression

  • The operands of a logical && or || shall be primary-expressions.

During preprocessing, violations of this rule are detected on the expressions in #if directives.

Allowed exception on associatively (a && b && c), (a || b || c).

12.6

Operands of logical operators (&&, || and !) should be effectively Boolean. Expression that are effectively Boolean should not be used as operands to operators other than (&&, || or !).

  • Operand of '!' logical operator should be effectively Boolean.

  • Left operand of '%s' logical operator should be effectively Boolean.

  • Right operand of '%s' logical operator should be effectively Boolean.

  • %s operand of '%s' is effectively Boolean. Boolean should not be used as operands to operators other than '&&', '||', '!', '=', '==', '!=' and '?:'.

The operand of a logical operator should be a Boolean data type. Although the C standard does not explicitly define the Boolean data type, the standard implicitly assumes the use of the Boolean data type.

Some operators may return Boolean-like expressions, for example, (var == 0).

Consider the following code:

unsigned char flag;
if (!flag)

The rule checker reports a violation of rule 12.6:

Operand of '!' logical
operator should be 
effectively Boolean.
The operand flag is not a Boolean but an unsigned char.

To be compliant with rule 12.6, the code must be rewritten either as

if (!( flag != 0))
or
if (flag == 0)

The use of the option -boolean-types may increase or decrease the number of warnings generated.

12.7

Bitwise operators shall not be applied to operands whose underlying type is signed

  • [~/Left Shift/Right shift/&] operator applied on an expression whose underlying type is signed. 

  • Bitwise ~ on operand of signed underlying type XX.

  • Bitwise [<<|>>] on left hand operand of signed underlying type XX.

  • Bitwise [& | ^] on two operands of s

The underlying type for an integer is signed when:

  • it does not have a u or U suffix

  • it is small enough to fit into a 64 bits signed number

12.8

The right hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left hand operand.

  • shift amount is negative

  • shift amount is bigger than 64

  • Bitwise [<< >>] count out of range [0 ..X] (width of the underlying type XX of the left hand operand - 1)..

The numbers that are manipulated in preprocessing directives are 64 bits wide so that valid shift range is between 0 and 63

Check is also extended onto bitfields with the field width or the width of the base type when it is within a complex expression

12.9

The unary minus operator shall not be applied to an expression whose underlying type is unsigned.

  • Unary - on operand of unsigned underlying type XX.

  • Minus operator applied to an expression whose underlying type is unsigned

The underlying type for an integer is signed when:

  • it does not have a u or U suffix

  • it is small enough to fit into a 64 bits signed number

12.10

The comma operator shall not be used.

The comma operator shall not be used.

 
12.11Evaluation of constant unsigned expression should not lead to wraparound.

Evaluation of constant unsigned integer expressions should not lead to wrap-around.

 
12.12The underlying bit representations of floating-point values shall not be used.The underlying bit representations of floating-point values shall not be used.

Warning when:

  • A float pointer is cast as a pointer to another data type. Casting a float pointer as a pointer to void does not generate a warning.

  • A float is packed with another data type. For example:

    union {
     float f;
     int i;
    } …
    

12.13

The increment (++) and decrement (--) operators should not be mixed with other operators in an expression

The increment (++) and decrement (--) operators should not be mixed with other operators in an expression

Warning when ++ or -- operators are not used alone.

Control Statement Expressions

N.MISRA DefinitionMessages in report filePolyspace Implementation
13.1

Assignment operators shall not be used in expressions that yield Boolean values.

Assignment operators shall not be used in expressions that yield Boolean values.

 

13.2

Tests of a value against zero should be made explicit, unless the operand is effectively Boolean

Tests of a value against zero should be made explicit, unless the operand is effectively Boolean

No warning is given on integer constants. Example: if (2)

The use of the option -boolean-types may increase or decrease the number of warnings generated.

13.3Floating-point expressions shall not be tested for equality or inequality.Floating-point expressions shall not be tested for equality or inequality.Warning on directs tests only.
13.4The controlling expression of a for statement shall not contain any objects of floating typeThe controlling expression of a for statement shall not contain any objects of floating typeIf for index is a variable symbol, checked that it is not a float.
13.5The three expressions of a for statement shall be concerned only with loop control
  • 1st expression should be an assignment.

  • Bad type for loop counter (XX).

  • 2nd expression should be a comparison.

  • 2nd expression should be a comparison with loop counter (XX).

  • 3rd expression should be an assignment of loop counter (XX).

  • 3rd expression: assigned variable should be the loop counter (XX).

  • The following kinds of for loops are allowed:

    (a) all three expressions shall be present;

    (b) the 2nd and 3rd expressions shall be present with prior initialization of the loop counter;

    (c) all three expressions shall be empty for a deliberate infinite loop.

Checked if the for loop index (V) is a variable symbol; checked if V is the last assigned variable in the first expression (if present). Checked if, in first expression, if present, is assignment of V; checked if in 2nd expression, if present, must be a comparison of V; Checked if in 3rd expression, if present, must be an assignment of V.
13.6Numeric variables being used within a for loop for iteration counting should not be modified in the body of the loop.Numeric variables being used within a for loop for iteration counting should not be modified in the body of the loop.Detect only direct assignments if the for loop index is known and if it is a variable symbol.
13.7

Boolean operations whose results are invariant shall not be permitted

  • Boolean operations whose results are invariant shall not be permitted. Expression is always true.

  • Boolean operations whose results are invariant shall not be permitted. Expression is always false.

  • Boolean operations whose results are invariant shall not be permitted.

During compilation, the checker covers comparisons with at least one constant operand. Some violations of this rule are reported through the Dead code and Useless if checkers.

The rule violation appears when you check whether an enum variable value lies between its lower and upper bound. The violation appears even if you increment or decrement the variable outside its bounds, for instance, in this for loop condition:

enum ec {RED, BLUE, GREEN} 
    col;
for(col=RED; col<=GREEN; 
    col++)
{}
An enum variable can potentially wrap around when incremented outside its range and the loop condition can be always true. To avoid the rule violation, you can cast the enum to an integer before the comparison, for instance:
enum ec {RED, BLUE, GREEN} 
   col;
for(col=RED; (int)col<=GREEN;
    col++ )
{}

Control Flow

N.MISRA DefinitionMessages in report filePolyspace Implementation
14.1

There shall be no unreachable code.

There shall be no unreachable code. 
14.2

All non-null statements shall either have at least one side effect however executed, or cause control flow to change

All non-null statements shall either:

  • have at least one side effect however executed, or

  • cause control flow to change

 
14.3

Before preprocessing, a null statement shall occur on a line by itself; it may be followed by a comment provided that the first character following the null statement is a white-space character.

A null statement shall appear on a line by itself

We assume that a ';' is a null statement when it is the first character on a line (excluding comments). The rule is violated when:

  • there are some comments before it on the same line.

  • there is a comment immediately after it

  • there is something else than a comment after the ';' on the same line.

14.4

The goto statement shall not be used.

The goto statement shall not be used.

 
14.5

The continue statement shall not be used.

The continue statement shall not be used.

 
14.6

For any iteration statement there shall be at most one break statement used for loop termination

For any iteration statement there shall be at most one break statement used for loop termination

 
14.7

A function shall have a single point of exit at the end of the function

A function shall have a single point of exit at the end of the function

 
14.8

The statement forming the body of a switch, while, do while or for statement shall be a compound statement

  • The body of a do while statement shall be a compound statement.

  • The body of a for statement shall be a compound statement.

  • The body of a switch statement shall be a compound statement

 
14.9

An if (expression) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement

  • An if (expression) construct shall be followed by a compound statement.

  • The else keyword shall be followed by either a compound statement, or another if statement

 
14.10

All if else if constructs should contain a final else clause.

All if else if constructs should contain a final else clause.

 

Switch Statements

N.MISRA DefinitionMessages in report filePolyspace Implementation
15.0

The MISRA C switch syntax shall be used.

switch statements syntax normative restrictions.

Warning on declarations or any statements before the first switch case.

Warning on label or jump statements in the body of switch cases.

On the following example, the rule is displayed in the log file at line 3:

1 ...
2 switch(index) {
3  var = var + 1; 
// RULE 15.0 
// violated
4case 1: ...

The code between switch statement and first case is checked as dead code by Polyspace. It follows ANSI standard behavior.

This rule is not considered as a required rule in the MISRA C:2004 rules for generated code. In generated code, if you find a violation of rule 15.0 that does not simultaneously violate a later rule in this group, justify the violation with appropriate comments.

15.1

A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement

A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement

 
15.2

An unconditional break statement shall terminate every non-empty switch clause

An unconditional break statement shall terminate every non-empty switch clause

Warning for each non-compliant case clause.

15.3

The final clause of a switch statement shall be the default clause

The final clause of a switch statement shall be the default clause

 
15.4

A switch expression should not represent a value that is effectively Boolean

A switch expression should not represent a value that is effectively Boolean

The use of the option -boolean-types may increase the number of warnings generated.

15.5

Every switch statement shall have at least one case clause

Every switch statement shall have at least one case clause

 

Functions

N.MISRA DefinitionMessages in report filePolyspace Implementation
16.1

Functions shall not be defined with variable numbers of arguments.

Function XX should not be defined as varargs.

 
16.2

Functions shall not call themselves, either directly or indirectly.

Function %s should not call itself.

The checker reports each function that calls itself, directly or indirectly. Even if several functions are involved in one recursion cycle, each function is individually reported.

You can calculate the total number of recursion cycles using the code complexity metric Number of Recursions.

16.3

Identifiers shall be given for all of the parameters in a function prototype declaration.

Identifiers shall be given for all of the parameters in a function prototype declaration.

Assumes Rule 8.6 is not violated.

16.4The identifiers used in the declaration and definition of a function shall be identical.The identifiers used in the declaration and definition of a function shall be identical.

Assumes that rules 8.8, 8.1 and 16.3 are not violated.

All occurrences are detected.

16.5

Functions with no parameters shall be declared with parameter type void.

Functions with no parameters shall be declared with parameter type void.

Definitions are also checked.

16.6The number of arguments passed to a function shall match the number of parameters.
  • Too many arguments to XX.

  • Insufficient number of arguments to XX.

Assumes that rule 8.1 is not violated.

This rule maps to ISO/IEC TS 17961 ID argcomp.

16.7

A pointer parameter in a function prototype should be declared as pointer to const if the pointer is not used to modify the addressed object.

Pointer parameter in a function prototype should be declared as pointer to const if the pointer is not used to modify the addressed object.

Warning if a non-const pointer parameter is either not used to modify the addressed object or is passed to a call of a function that is declared with a const pointer parameter.

16.8

All exit paths from a function with non-void return type shall have an explicit return statement with an expression.

Missing return value for non-void function XX.

Warning when a non-void function is not terminated with an unconditional return with an expression.

16.9

A function identifier shall only be used with either a preceding &, or with a parenthesized parameter list, which may be empty.

Function identifier XX should be preceded by a & or followed by a parameter list.

 
16.10

If a function returns error information, then that error information shall be tested.

If a function returns error information, then that error information shall be tested.

The checker flags functions with non-void return if the return value is not used or not explicitly cast to a void type.

The checker does not flag the functions memcpy, memset, memmove, strcpy, strncpy, strcat, strncat because these functions simply return a pointer to their first arguments.

Pointers and Arrays

N.MISRA DefinitionMessages in report filePolyspace Implementation
17.1

Pointer arithmetic shall only be applied to pointers that address an array or array element.

Pointer arithmetic shall only be applied to pointers that address an array or array element.

 
17.2Pointer subtraction shall only be applied to pointers that address elements of the same arrayPointer subtraction shall only be applied to pointers that address elements of the same array.Polyspace reports a violation when you subtract that are null or that point to elements in different arrays.
17.3

>, >=, <, <= shall not be applied to pointer types except where they point to the same array.

>, >=, <, <= shall not be applied to pointer types except where they point to the same array.

Polyspace reports a violation when you compare pointers that are null or that point to elements in different arrays. The relational operators for the comparison are >, <, >=, and <=.
17.4Array indexing shall be the only allowed form of pointer arithmetic.Array indexing shall be the only allowed form of pointer arithmetic.

Warning on:

  • Operations on pointers. (p+I, I+p, and p-I, where p is a pointer and I an integer).

  • Array indexing on nonarray pointers.

17.5A type should not contain more than 2 levels of pointer indirectionA type should not contain more than 2 levels of pointer indirection 
17.6The address of an object with automatic storage shall not be assigned to an object that may persist after the object has ceased to exist.Pointer to a parameter is an illegal return value. Pointer to a local is an illegal return value.

Warning when assigning address to a global variable, returning a local variable address, or returning a parameter address.

This rule maps to ISO/IEC TS 17961 ID accfree.

Structures and Unions

N.MISRA DefinitionMessages in report filePolyspace Implementation
18.1

All structure or union types shall be complete at the end of a translation unit.

All structure or union types shall be complete at the end of a translation unit.

Warning for all incomplete declarations of structs or unions.

18.2

An object shall not be assigned to an overlapping object.

  • An object shall not be assigned to an overlapping object.

  • Destination and source of XX overlap, the behavior is undefined.

 
18.4

Unions shall not be used

Unions shall not be used.

 

Preprocessing Directives

N.MISRA DefinitionMessages in report filePolyspace Implementation
19.1

#include statements in a file shall only be preceded by other preprocessors directives or comments

#include statements in a file shall only be preceded by other preprocessors directives or comments

A message is displayed when a #include directive is preceded by other things than preprocessor directives, comments, spaces or “new lines”.

19.2

Nonstandard characters should not occur in header file names in #include directives

  • A message is displayed on characters ', " or /* between < and > in #include <filename>

  • A message is displayed on characters ', or /* between " and " in #include "filename"

 
19.3

The #include directive shall be followed by either a <filename> or "filename" sequence.

  • '#include' expects "FILENAME" or <FILENAME>

  • '#include_next' expects "FILENAME" or <FILENAME>

 
19.4C macros shall only expand to a braced initializer, a constant, a parenthesized expression, a type qualifier, a storage class specifier, or a do-while-zero construct.

Macro '<name>' does not expand to a compliant construct.

We assume that a macro definition does not violate this rule when it expands to:

  • a braced construct (not necessarily an initializer)

  • a parenthesized construct (not necessarily an expression)

  • a number

  • a character constant

  • a string constant (can be the result of the concatenation of string field arguments and literal strings)

  • the following keywords: typedef, extern, static, auto, register, const, volatile, __asm__ and __inline__

  • a do-while-zero construct

19.5

Macros shall not be #defined and #undefd within a block.

  • Macros shall not be #define’d within a block.

  • Macros shall not be #undef’d within a block.

 
19.6

#undef shall not be used.

#undef shall not be used.

 
19.7

A function should be used in preference to a function like-macro.

A function should be used in preference to a function like-macroMessage on all function-like macro definitions.
19.8

A function-like macro shall not be invoked without all of its arguments

  • arguments given to macro '<name>'

  • macro '<name>' used without args.

  • macro '<name>' used with just one arg.

  • macro '<name>' used with too many (<number>) args.

 
19.9

Arguments to a function-like macro shall not contain tokens that look like preprocessing directives.

Macro argument shall not look like a preprocessing directive.

This rule is detected as violated when the '#' character appears in a macro argument (outside a string or character constant)

19.10

In the definition of a function-like macro each instance of a parameter shall be enclosed in parentheses unless it is used as the operand of # or ##.

Parameter instance shall be enclosed in parentheses.

If x is a macro parameter, the following instances of x as an operand of the # and ## operators do not generate a warning: #x, ##x, and x##. Otherwise, parentheses are required around x.

The software does not generate a warning if a parameter is reused as an argument of a function or function-like macro. For example, consider a parameter x. The software does not generate a warning if x appears as (x) or (x, or ,x) or ,x,.

19.11

All macro identifiers in preprocessor directives shall be defined before use, except in #ifdef and #ifndef preprocessor directives and the defined() operator.

'<name>' is not defined.

 
19.12

There shall be at most one occurrence of the # or ## preprocessor operators in a single macro definition.

More than one occurrence of the # or ## preprocessor operators.

 
19.13

The # and ## preprocessor operators should not be used

Message on definitions of macros using # or ## operators

 
19.14

The defined preprocessor operator shall only be used in one of the two standard forms.

'defined' without an identifier.

 
19.15Precautions shall be taken in order to prevent the contents of a header file being included twice.Precautions shall be taken in order to prevent multiple inclusions.

When a header file is formatted as,

#ifndef <control macro>
#define <control macro> 
<contents> #endif

or,

#ifndef <control macro>
#error ...
#else 
#define <control macro> 
<contents> #endif

it is assumed that precautions have been taken to prevent multiple inclusions. Otherwise, a violation of this MISRA rule is detected.

19.16

Preprocessing directives shall be syntactically meaningful even when excluded by the preprocessor.

directive is not syntactically meaningful.

 
19.17

All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if or #ifdef directive to which they are related.

  • '#elif' not within a conditional.

  • '#else' not within a conditional.

  • '#elif' not within a conditional.

  • '#endif' not within a conditional.

  • unbalanced '#endif'.

  • unterminated '#if' conditional.

  • unterminated '#ifdef' conditional.

  • unterminated '#ifndef' conditional.

 

Standard Libraries

N.MISRA DefinitionMessages in report filePolyspace Implementation
20.1

Reserved identifiers, macros and functions in the standard library, shall not be defined, redefined or undefined.

  • The macro '<name> shall not be redefined.

  • The macro '<name> shall not be undefined.

 
20.2

The names of standard library macros, objects and functions shall not be reused.

Identifier XX should not be used.

In case a macro whose name corresponds to a standard library macro, object or function is defined, the rule that is detected as violated is 20.1.

Tentative definitions are considered as definitions. For objects with file scope, tentative definitions are declarations that:

  • Do not have initializers.

  • Do not have storage class specifiers, or have the static specifier

20.3

The validity of values passed to library functions shall be checked.

Validity of values passed to library functions shall be checked

Warning for argument in library function call if the following are all true:

  • Argument is a local variable

  • Local variable is not tested between last assignment and call to the library function

  • Library function is a common mathematical function

  • Corresponding parameter of the library function has a restricted input domain.

The library function can be one of the following : sqrt, tan, pow, log, log10, fmod, acos, asin, acosh, atanh, or atan2.

You might be using a custom library of mathematical functions. If a custom library function have the same domain and range as another function from the standard library, you can extend this checker to check the custom library function. See Extend Bug Finder Checkers for Standard Library Functions to Custom Libraries.

A default Bug Finder analysis might not raise a violation of this rule when the input values are unknown and only a subset of inputs can cause an issue. To check for violations caused by specific system input values, run a stricter Bug Finder analysis. See Extend Bug Finder Checkers to Find Defects from Specific System Input Values.

By default, a Bug Finder analysis does not recognize infinities and NaNs. Operations that results in infinities and NaNs might be flagged as defects. To handle infinities and NaN values in your code, use the option Consider non finite floats (-allow-non-finite-floats).

20.4

Dynamic heap memory allocation shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the dynamic heap memory allocation functions are actually macros and the macro is expanded in the code, this rule is detected as violated. Assumes rule 20.2 is not violated.

20.5

The error indicator errno shall not be used

The error indicator errno shall not be used

Assumes that rule 20.2 is not violated

20.6

The macro offsetof, in library <stddef.h>, shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

Assumes that rule 20.2 is not violated

20.7

The setjmp macro and the longjmp function shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the longjmp function is actually a macro and the macro is expanded in the code, this rule is detected as violated. Assumes that rule 20.2 is not violated

20.8

The signal handling facilities of <signal.h> shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case some of the signal functions are actually macros and are expanded in the code, this rule is detected as violated. Assumes that rule 20.2 is not violated

20.9

The input/output library <stdio.h> shall not be used in production code.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the input/output library functions are actually macros and are expanded in the code, this rule is detected as violated. Assumes that rule 20.2 is not violated

20.10

The library functions atof, atoi and atoll from library <stdlib.h> shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the atof, atoi and atoll functions are actually macros and are expanded, this rule is detected as violated. Assumes that rule 20.2 is not violated

20.11

The library functions abort, exit, getenv and system from library <stdlib.h> shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the abort, exit, getenv and system functions are actually macros and are expanded, this rule is detected as violated. Assumes that rule 20.2 is not violated

20.12

The time handling functions of library <time.h> shall not be used.

  • The macro '<name> shall not be used.

  • Identifier XX should not be used.

In case the time handling functions are actually macros and are expanded, this rule is detected as violated. Assumes that rule 20.2 is not violated

Runtime Failures

N.MISRA DefinitionMessages in report filePolyspace Implementation
21.1

Minimization of runtime failures shall be ensured by the use of at least one of:

  • static verification tools/techniques;

  • dynamic verification tools/techniques;

  • explicit coding of checks to handle runtime faults.

  

Unsupported MISRA C:2004 and MISRA AC AGC Rules

The Polyspace coding rules checker does not check the following MISRA C:2004 coding rules. These rules cannot be enforced because they are outside the scope of Polyspace software. They may concern documentation, dynamic aspects, or functional aspects of MISRA rules. The Additional Information column describes the reason each rule is not checked.

Environment

RuleDescriptionAdditional Information
1.2 (Required)

No reliance shall be placed on undefined or unspecified behavior

Not statically checkable unless the data dynamic properties is taken into account

1.3 (Required)

Multiple compilers and/or languages shall only be used if there is a common defined interface standard for object code to which the language/compilers/assemblers conform.

It is a process rule method.

1.4 (Required)

The compiler/linker/Identifiers (internal and external) shall not rely on significance of more than 31 characters. Furthermore the compiler/linker shall be checked to ensure that 31 character significance and case sensitivity are supported for external identifiers.

To observe this rule, check your compiler documentation.

1.5 (Advisory)

Floating point implementations should comply with a defined floating point standard.

To observe this rule, check your compiler documentation.

Documentation

RuleDescriptionAdditional Information
3.1 (Required)

All usage of implementation-defined behavior shall be documented.

To observe this rule, check your compiler documentation. Error detection is based on undefined behavior, according to choices made for implementation- defined constructions.

3.2 (Required)

The character set and the corresponding encoding shall be documented.

To observe this rule, check your compiler documentation.

3.3 (Advisory)

The implementation of integer division in the chosen compiler should be determined, documented and taken into account.

To observe this rule, check your compiler documentation.

3.5 (Required)

The implementation-defined behavior and packing of bitfields shall be documented if being relied upon.

To observe this rule, check your compiler documentation.

3.6 (Required)

All libraries used in production code shall be written to comply with the provisions of this document, and shall have been subject to appropriate validation.

To observe this rule, check your compiler documentation.

Structures and Unions

RuleDescriptionAdditional Information
18.3 (Required)

An area of memory shall not be reused for unrelated purposes.

"purpose" is functional design issue.