Working with Static Code Analyzers in C will render a coding standard (a "safe" C Language subset) on the top of a particular compiler implementation. It helps prevent unsafe constructs, as well as undefined behavior whenever an embedded application has safety certification burden. Using it results in a trade-off between the range of possibilities the C Language spec provides versus the stricter rules that stems from the requirements.
According to the IAR C-STAT documentation, the UNION-type-punning
is a cross-check covering rules from multiple standards and it is enabled by default. For example, the CERT EXP39-C explanation:
If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called “type punning”). This might be a trap representation.
The full warning message generated by the presented snippet looks like:
"main.c",18 Severity-Medium[UNION-type-punning]:Union 'mainValue' is written as 'valNum', then read as another field.
"main.c",17: ! - Write to union field: mainValue.valNum = tempData
"main.c",18: ! - Read from union field: mainValue.valNumH
The myFunction()
requires 8-bit access. It could be rewritten in the following way to become compliant to the UNION-type-punning
rule:
uint16_t myFunction(uint16_t tempData) {
uint8_t myData[8];
valueExp mainValue;
mainValue.valNumH=((tempData & 0xFF00U) >> 8);
mainValue.valNumL=(tempData & 0x00FFU);
myData[5]=mainValue.valNumH;
/* .... */
One workaround is to suppress this check for the affected line, where valNumH
is read in myFunction()
:
uint16_t myFunction(uint16_t tempData) {
uint8_t myData[8];
valueExp mainValue;
mainValue.valNum=tempData;
#pragma cstat_suppress="UNION-type-punning"
myData[5]=mainValue.valNumH;
/* ... */
misra
- nor is a MISRA rule cited by the checker?