Main Content

MISRA C:2023 Rule 11.9

The macro NULL shall be the only permitted form of integer null pointer constant

Since R2024a

Description

Rule Definition

The macro NULL shall be the only permitted form of integer null pointer constant.

Rationale

The following expressions allow the use of a null pointer constant:

  • Assignment to a pointer

  • The == or != operation, where one operand is a pointer

  • The ?: operation, where one of the operands on either side of : is a pointer

Using NULL rather than 0 makes it clear that a null pointer constant was intended.

Polyspace Implementation

The checker flags the assignment of the constant zero to pointers, equalities (or inequalities) comparing pointers with the constant zero, and other similar expressions listed in the MISRA C™: 2012 documentation.

Following the updates in MISRA C: 2012 Technical Corrigendum 1, the checker allows the use of {0} to initialize aggregates containing only pointers, for instance, arrays of pointers or structures (or unions) with only a pointer field. If an aggregate contains multiple fields, the initialization is still flagged. In these cases, you should use the macro NULL for pointer fields and 0 for integer fields to distinguish between them.

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

void main(void) {

    int *p1 = 0;              /* Non-compliant */ 
    int *p2 = ( void * ) 0;   /* Compliant     */ 

#define MY_NULL_1 0    /* Non-compliant */
#define MY_NULL_2 ( void * ) 0  

    if ( p1 == MY_NULL_1 )
    { }
    if ( p2 == MY_NULL_2 )    /* Compliant     */
    { }

}

In this example, the rule is violated when the constant 0 is used instead of (void*) 0 for pointer assignments and comparisons.

void init () {
    int *myArray[5] = {0}; //Compliant

    struct structPtr { 
        int *ptr;
    } structPtr = {0}; //Compliant

    struct StructIntPtr { 
        int data;
        int *ptr;
    } StructIntPtr = {0,0}; //Non-compliant
}

Following the updates in MISRA C: 2012 Technical Corrigendum 1, the checker allows the use of {0} to initialize aggregates containing only pointers such as:

  • Arrays of pointers, for instance, myArray

  • Structures with one pointer field only, for instance, structPtr

If an aggregate contains multiple fields, such as StructIntPtr, the initialization is still flagged. In these cases, you should use the macro NULL for pointer fields and 0 for integer fields to distinguish between them.

Check Information

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

Version History

Introduced in R2024a