Main Content

MISRA C:2012 Rule 11.7

A cast shall not be performed between pointer to object and a non-integer arithmetic type

Description

Rule Definition

A cast shall not be performed between pointer to object and a non-integer arithmetic type.

Rationale

This rule covers types that are essentially Boolean, character, enum or floating.

  • If an essentially Boolean, character or enum variable is cast to a pointer, the resulting pointer can be incorrectly aligned. The incorrect alignment causes undefined behavior. If a pointer is cast to one of those types, the resulting value can be outside the allowed range for the type.

  • Casts to or from a pointer to a floating type results in undefined behavior.

Troubleshooting

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

Examples

expand all

int foo(void) {

    short *p;
    float  f;
    long  *l;

    f = (float)   p;              /* Non-compliant */
    p = (short *) f;              /* Non-compliant */

    l = (long *)  p;              /* Compliant */
}

In this example, the rule is violated when:

  • The pointer p is cast to float.

  • A float variable is cast to a pointer to short.

Casting between a pointer and a non-integerer variable might cause a compilation failure. Polyspace® flags such casts.

The rule is not violated when the pointer p is cast to long*.

Check Information

Group: Pointer Type Conversions
Category: Required
AGC Category: Required

Version History

Introduced in R2014b

expand all