Main Content

MISRA C:2023 Rule 8.13

A pointer should point to a const-qualified type whenever possible

Since R2024a

Description

Rule Definition

A pointer should point to a const-qualified type whenever possible.

Rationale

This rule ensures that you do not inadvertently use pointers to modify objects.

Polyspace Implementation

The rule checker flags a pointer to a non-const function parameter if the pointer does not modify the addressed object. The assumption is that the pointer is not meant to modify the object and so must point to a const-qualified type. Polyspace® does not raise a flag if the data pointed to by a nonconst pointer is modified by using a copy of the 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 <string.h>

typedef unsigned short uint16_t;

uint16_t ptr_ex(uint16_t *p) {      /* Non-compliant */
    return *p;
}

char last_char(char * const s){     /* Non-compliant */
    return s[strlen(s) - 1u];
}

uint16_t first(uint16_t a[5]){      /* Non-compliant */
    return a[0];
}

This example shows three different noncompliant pointer parameters.

  • In the ptr_ex function, p does not modify an object. However, the type to which p points is not const-qualified, so it is noncompliant.

  • In last_char, the pointer s is const-qualified but the type it points to is not. This parameter is noncompliant because s does not modify an object.

  • The function first does not modify the elements of the array a. However, the element type is not const-qualified, so a is also noncompliant.

Correction — Use const Keywords

One possible correction is to add const qualifiers to the definitions.

#include <string.h>

typedef unsigned short uint16_t;

uint16_t ptr_ex(const uint16_t *p){     /* Compliant */
    return *p;
}

char last_char(const char * const s){   /* Compliant */
    return s[strlen( s ) - 1u];
}

uint16_t first(const uint16_t a[5]) {   /* Compliant */
    return a[0];
}

Check Information

Group: Declarations and Definitions
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a