Main Content

MISRA C:2023 Rule 11.2

Conversions shall not be performed between a pointer to an incomplete type and any other type

Since R2024a

Description

Rule Definition

Conversions shall not be performed between a pointer to an incomplete type and any other type.

Rationale

An incomplete type is a type that does not contain sufficient information to determine its size. For example, the statement struct s; describes an incomplete type because the fields of s are not defined. The size of a variable of type s cannot be determined.

Conversions to or from a pointer to an incomplete type result in undefined behavior. Typically, a pointer to an incomplete type is used to hide the full representation of an object. This encapsulation is broken if another pointer is implicitly or explicitly cast to such a pointer.

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

#include <stdio.h> 
struct s *sp;
struct t *tp;
short  *ip;
struct ct *ctp1;
struct ct *ctp2;


void foo(void) {

    ip = (short *) sp;            /* Non-compliant */
    sp = (struct s *) 1234;       /* Non-compliant */
    tp = (struct t *) sp;         /* Non-compliant */
    ctp1 = (struct ct *) ctp2;    /* Compliant */

    /* You can convert a null pointer constant to 
     * a pointer to an incomplete type */
    sp = NULL;                    /* Compliant - exception  */

    /* A pointer to an incomplete type may be converted into void */
    struct s *f(void);
    (void) f();                   /* Compliant - exception  */

}

In this example, types s, t and ct are incomplete. The rule is violated when:

  • The variable sp with an incomplete type is cast to a basic type.

  • The variable sp with an incomplete type is cast to a different incomplete type t.

The rule is not violated when:

  • The variable ctp2 with an incomplete type is cast to the same incomplete type.

  • The NULL pointer is cast to the variable sp with an incomplete type.

  • The return value of f with incomplete type is cast to void.

Check Information

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

Version History

Introduced in R2024a