MISRA:Cast between a pointer to volatile object and an integral type?

不羁岁月 提交于 2020-06-29 09:01:31


I have following code section:

typedef volatile struct REG_Base{

#define address (0xFFF45556)


 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?



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 and b 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.