V2589. MISRA. Casts between a pointer and a non-integer arithmetic type should not be performed.
This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guide.
This rule only applies to programs written in C. A cast between a non-integer arithmetic type and a pointer may lead to undefined behavior.
The MISRA standard introduces the Essential type model, where a variable might have the following types:
- Boolean, if it operates true/false values: '_Bool';
- signed, if it operates signed integer numbers, or is an unnamed enum: 'signed char', 'signed short', 'signed int', 'signed long', 'signed long long', 'enum { .... };';
- unsigned, if it operates unsigned integer numbers: 'unsigned char', 'unsigned short', 'unsigned int', 'unsigned long', 'unsigned long long';
- floating, if it operates floating-point numbers: 'float', 'double', 'long double';
- character, if it operates only characters: 'char';
- Named enum, if it operates a named set of user-defined values: 'enum name { .... };'
A cast between essential 'Boolean', 'character' or 'enum' and a pointer may lead to a misaligned pointer, which causes undefined behavior. Example:
enum Nums
{
ONE,
TWO,
....
};
double* bar(Nums num)
{
....
return (double*)num;
}
A cast between a pointer and essential types described above may result in a value unrepresentable within the destination essential type, which also leads to undefined behavior. Example:
void foo(void)
{
....
char *a = "something";
char b = a;
....
}
A cast between an essential 'floating' type and a pointer leads to undefined behavior. Example:
void foo(short *p)
{
// ....
float f = (float) p;
// ....
}
This diagnostic is classified as:
|