Main Content

Qualifier removed in conversion

Variable qualifier is lost during conversion

Description

This checker is deactivated in a default Polyspace® as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

This defect occurs during a pointer conversion when one pointer has a qualifier and the other does not. For example, when converting from a const int* to an int*, the conversion removes the const qualifier.

This defect applies only for projects in C.

Risk

Qualifiers such as const or volatile in a pointer declaration:

const int* ptr;
imply that the underlying object is const or volatile. These qualifiers act as instructions to the compiler. For instance, a const object is not supposed to be modified in the code and a volatile object is not supposed to be optimized away by the compiler.

If a second pointer points to the same object but does not use the same qualifier, the qualifier on the first pointer is no longer valid. For instance, if a const int* pointer and an int* pointer point to the same object, you can modify the object through the second pointer and violate the contract implied by the const qualifier in the first pointer.

Fix

If you intend to convert from one pointer to another, declare both pointers with the same qualifiers.

Examples

expand all

void implicit_cast(void) {
    const char  cc, *pcc = &cc;
    char * quo;

    quo = &cc;
    quo = pcc;

    read(quo);
}

During the assignment to the character q, the variables, cc and pcc, are converted from const char to char. The const qualifier is removed during the conversion causing a defect.

Correction — Add Qualifiers

One possible correction is to add the same qualifiers to the new variables. In this example, changing q to a const char fixes the defect.

void implicit_cast(void) {
    const char  cc, *pcc = &cc;
    const char * quo;

    quo = &cc;
    quo = pcc;

    read(quo);
}
Correction — Remove Qualifiers

One possible correction is to remove the qualifiers in the converted variable. In this example, removing the const qualifier from the cc and pcc initialization fixes the defect.

void implicit_basic_cast(void) {
    char  cc, *pcc = &cc;
    char * quo;

    quo = &cc;
    quo = pcc;

    read(quo);
}

Result Information

Group: Programming
Language: C
Default: Off
Command-Line Syntax: QUALIFIER_MISMATCH
Impact: Low

Version History

Introduced in R2013b