问题
I have following code section:
----------header---------------------
typedef volatile struct REG_Base{
a;
b;
}REG_t
#define address (0xFFF45556)
------------------------------------
--------Source-----------------------
LOCAL REG_t *pToREG;
pToREG= (REG_t *) address;
-------------------------------------
I got on the last line the MISRA message "Cast between a pointer to volatile object and an integral type".
Any idea how to avoid this message?
Thx!
回答1:
MISRA has an advisory rule which bans casts from integers to pointers. The rationale is that they are concerned with the poorly defined behavior involved in case the integer cannot represent the pointer, or in case of misalignment.
This is one of the overly pedantic rules and it is just advisory. Most embedded systems will deviate from the rule.
That being said, your code contains some questionable things:
- The volatile qualifier should not be part of the typedef.
- The
a
andb
declarations doesn't make any sense, are they some sort of ugly macros? - Mapping a struct to a physical address is not portable and safe. The struct might contain padding, the address might not be correctly aligned for the given types. At the very least, you need some means to assure there are no struct padding, preferably a static assert.
Also note that MISRA requires the integer constant to be written as 0xFFF45556u
. This is not a bad idea, because 0xFFF45556
is of type unsigned int
, while for example 0x7FFFFFFF
is of type signed int. These things might lead to subtle bugs related to implicit type promotions unless you are careful.
来源:https://stackoverflow.com/questions/36552165/misracast-between-a-pointer-to-volatile-object-and-an-integral-type