[C-safe-secure-studygroup] MISRA and packed structures

Martin Sebor msebor at gmail.com
Wed Nov 28 23:33:41 GMT 2018


On 11/27/18 5:05 AM, Robert Seacord wrote:
> Is there any MISRA rules which disallow the use of packed structures?

FWIW, a problem related to struct packing that has been reported
a few times to GCC is due to the use of the feature with a user-
defined struct that contains a member of an overaligned type such
as a mutex or an atomic variable.  This is especially insidious
when the overaligned type is itself a member of some other struct,
like this:

   struct __atttribute__ ((packed)) UserDefined
   {
     int x;
     struct SomeOtherType y;   // contains a mutex
   };

When the mutex or atomic variable in SomeOtherType is
an implementation detail of the type not meant to be directly
used by its clients it's typically not documented and so users
have no idea that it's even there.  When they pass the member
y to its API it can crash because of an unaligned access even
on architectures with relaxed alignment.

To help prevent this kind of a problem GCC 8 added attribute
warn_if_not_aligned that the authors of SomeOtherType and
pthread_mutex_t can declare their types with to have GCC issue
a warning when object of the types are not properly aligned.

Martin



More information about the C-safe-secure-studygroup mailing list