Question on MISRA C:2012- Rule 10.3 in polyspace code prover 2019a

19 views (last 30 days)
Assuming that I have the following structure and enum:
Code:
typedef struct s{
unsigned int a:5;
unsigned int b:1;
unsigned int c:1;
} s;
typedef enum e{
ZERO = 0,
ONE = 1,
TWO = 2,
THREE = 3
} e;
Why does the following code trigger rule 10.3?
Code:
s fcn(void)
{
s test;
test.a = (unsigned int) THREE; // MISRA C:2012 10.3 violation
test.a = (unsigned char) THREE; // MISRA C:2012 10.3 violation
return test;
}

Accepted Answer

Anirban
Anirban on 27 Jan 2022
Edited: Anirban on 27 Jan 2022
The first violation is a genuine violation while the second violation is a Polyspace bug that has been fixed in R2019b. Since R2019b, the messages are also clearer and help you understand the essential types of expressions.
For bit-fields, the "essential type" is the smallest type that can hold the variable. See a brief description of essential types in context of MISRA C:2012 Rule 10.x. This means that the essential type of test.a is unsigned char (or more precisely, unsigned 8 bits integer). Therefore, the assignment of an unsigned int (or more precisely, unsigned 32 bits integer) to test.a violates the rule while the assignment of an unsigned char does not.
In releases R2019b and later, you will not see the second violation. To be precise, this was not a bug in R2019a but a very strict interpretation of the rule (it prevented any cast where the types had different sizes).

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!