rationale behind Misra 2012 not allowing cast between different pointers

thunderbird picture thunderbird · Feb 17, 2016 · Viewed 7.5k times · Source

I am currently working on a project which requires the code to be Misra 2012 compliant. Throughout the project we have lots of required misra warnings telling us we cant convert pointer to one type to a pointer to another type. Things as simple as void *memcpy(void *to, const void *from, size_t n) produce two Misra Required warnings since both to and from need to be type-casted to void* and const void* respectively. Conversion from void* to a pointer to any other type also gives a Misra warning.

My question is how does Misra expect malloc and everything else to work without any warnings being thrown? Even converting a void* buffer to uint8_t* buffer to parse abuffer byte by byte and fill up all the elements of a structure structure will throw numerous warnings?

Instead of these warnings could it not just show use a note or info asking us to double check packing, alignment and anything else that might go wrong?

Answer

Roberto Bagnara picture Roberto Bagnara · Feb 29, 2016

I would like to go back to what the OP asked and get a few things straight. First of all, there is no problem in calling void *memcpy(void *to, const void *from, size_t n), as a conversion of a pointer to object to a void pointer does not violate any MISRA-C:2012 guideline. In other words, any tool producing violations for that is simply buggy.

Secondly, before coming to any conclusion it is important to read what Rule 11.5, the relevant MISRA-C:2012 guideline, actually says, that is:

  Rule 11.5
  A conversion should not be performed from pointer to void into
  pointer to object

  Category Advisory
  Analysis Decidable, Single Translation Unit
  Applies to C90, C99

  Rationale
  Conversion of a pointer to void into a pointer to object may result
  in a pointer that is not correctly aligned, resulting in undefined
  behaviour. It should be avoided where possible but may be necessary,
  for example when dealing with memory allocation functions. If
  conversion from a pointer to object into a pointer to void is used,
  care should be taken to ensure that any pointers produced do not
  give rise to the undefined behaviour discussed under Rule 11.3.

Observations:

  1. it is an advisory rule (i.e., neither required nor mandatory), so it can be deviated, and MISRA defined the correct deviation process;
  2. converting a pointer to object to a pointer to void is fine: it is the other way around that is problematic;
  3. the rationale explicitly mentions memory allocation functions (and, yes, a program that uses dynamic memory allocation can be made compliant to MISRA-C:2012);
  4. the rationale provides guidance on what to do when converting pointers to objects to pointers to void, perfectly in line with that the OP would like to have ("info asking us to double check packing, alignment and anything else that might go wrong").