Main Content

CERT C: Rec. EXP05-C

Do not cast away a const qualification

Description

Rule Definition

Do not cast away a const qualification.1

Polyspace Implementation

The rule checker checks for Cast to pointer that removes const qualification.

Examples

expand all

Issue

Polyspace® flags both implicit and explicit conversions that violate this rule.

Risk

This rule forbids casts from a pointer to a const object to a pointer that does not point to a const object.

Such casts violate type qualification. For example, the const qualifier indicates the read-only status of an object. If a cast removes the qualifier, the object is no longer read-only.

Example - Casts That Remove Qualifiers
void foo(void) {

    /* Cast on simple type */
    unsigned short           x;
    unsigned short * const   cpi = &x;  /* const pointer */
    unsigned short * const  *pcpi;   /* pointer to const pointer */
    unsigned short **ppi;
    const unsigned short    *pci;    /* pointer to const */
    unsigned short          *pi;

    pi = cpi;                        /* Compliant - no cast required */
    pi  = (unsigned short *)  pci;   /* Non-compliant */
    ppi = (unsigned short **)pcpi;   /* Non-compliant */
}

In this example, the variables pci and pcpi have the const qualifier in their type. The rule is violated when the variables are cast to types that do not have the const qualifier.

Even though cpi has a const qualifier in its type, the rule is not violated in the statement p=cpi;. The assignment does not cause a type conversion because both p and cpi have type unsigned short.

Check Information

Group: Rec. 03. Expressions (EXP)

Version History

Introduced in R2019a


1 This software has been created by MathWorks incorporating portions of: the “SEI CERT-C Website,” © 2017 Carnegie Mellon University, the SEI CERT-C++ Web site © 2017 Carnegie Mellon University, ”SEI CERT C Coding Standard – Rules for Developing safe, Reliable and Secure systems – 2016 Edition,” © 2016 Carnegie Mellon University, and “SEI CERT C++ Coding Standard – Rules for Developing safe, Reliable and Secure systems in C++ – 2016 Edition” © 2016 Carnegie Mellon University, with special permission from its Software Engineering Institute.

ANY MATERIAL OF CARNEGIE MELLON UNIVERSITY AND/OR ITS SOFTWARE ENGINEERING INSTITUTE CONTAINED HEREIN IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.

This software and associated documentation has not been reviewed nor is it endorsed by Carnegie Mellon University or its Software Engineering Institute.