>
>
>
V2611. MISRA. Casts between a pointer t…


V2611. MISRA. Casts between a pointer to an incomplete type and any other type shouldn't be performed.

This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) guidelines for software development.

This rule applies only to C. Casts, that involve pointers to an incomplete type, may result in an incorrectly assigned pointer. This may lead to undefined behavior. The same happens when a developer attempts casts between pointers to incomplete types - and floating point numbers.

Pointers to incomplete types are also used to hide the implementation (the PIMPL idiom). Casting to a pointer to an object breaks this encapsulation.

Example:

typedef struct _First First;
typedef struct _Second 
{
    int someVar;
} Second;

void foo(void)
{
    First *f;
    Second t;
    ...
    f = &t;                // <=
    ...
}

Second* bar(First *ptr)
{
    return (Second*)ptr;   // <=
}

In the code above, two structures are declared - 'First' and 'Second'. Note that the 'First' type is incomplete, because there's no definition for it. Then the 'foo' function indirectly casts a pointer to an incomplete type. While the 'bar' function does a direct cast from an incomplete type to a complete one. Both of these cases can lead to undefined behavior.

There are two exceptions to this rule:

  • The null pointer constant ('NULL') can be cast to a pointer to an incomplete type.
  • A pointer to an incomplete type can be converted to 'void'.

The 'baz' function below demonstrates both cases:

typedef struct _First First;

First* foo(void);

void baz(void)
{
    First *f = NULL;
    (void)foo();
}

This diagnostic is classified as:

  • MISRA-C-11.2