[previous] 0311 [next] Dangerous pointer cast results in loss of const qualification.
Pointers

A cast is being applied to a pointer addressing 'const' data and the cast has the effect of removing the 'const' qualification. This is dangerous because a pointer is created which can overwrite data which might otherwise be protected.

According to the ISO:C Standard (6.3.16.1), a pointer can only be assigned to another pointer if "both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all of the qualifiers of the type pointed to by the right". This language restriction ensures that the purpose of type qualifiers is preserved in assignment operations, function arguments and function return expressions. An assignment statement which violates this rule will generate the constraint error message 0562. However, by using a cast, type qualification can be overriden.

For example:


/*PRQA S 2017,3198,3199,3203,3227,3408,3602 ++*/

void foo(const int *pci)
{
    int  *pi;

    pi = pci;                           /* Message 0562 - Constraint Error */

    pi = (int *)pci;                    /* Message 0311                    */
}

QA·C Source Code Analyser 8.1.2
© 2013 Programming Research.
www.programmingresearch.com
Personality Groups | Glossary | Message Index Contents