Search code examples
cmisraflexible-array-member

Change of flexible array into pointer


I am working to get rid of MISRA violations coming in my C code. It is violating rule 18.7.

struct abc {
  struct header;
  uint8_t data[]; /* Line 1 */
};

Here, Line 1 is causing the MISRA violations.

I tried to convert it into:

struct abc {
  struct header;
  uint8_t *data;
};

Can we do like the above or is it violating something ?


Solution

  • Your solution is semantically different and won't work even if it clears the violation.

    The intent here is to create a structure that can act as a header for the contiguous data that follows it. So for example if you have:

    struct Message
    {
        struct abc info ;
        char data[128] ;
    }  message ;
    

    Such that message.info.data and message.data refer to the same thing and casting a struct abc to a struct Message allows a function to be defined for passing any object with a struct abc header. Effectively supporting polymorphism in C.

    Replacing it with:

    struct abc 
    {
      struct header;
      uint8_t* data;
    };
    

    is semantically different because the data member does not refer to the data contiguous with header. The copy semantics also differ, and it is unlikely in the context of the code that uses the original structure that it will work as intended.

    GCC supports the following syntax:

    struct abc 
    {
      struct header;
      uint8_t data[0] ;
    } ;
    

    but it is likely that is not MISRA compliant either. A compliant solution is to have:

    struct abc 
    {
      struct header;
      uint8_t data[1] ;
    } ;
    

    But that inserts an extra character and any code that uses this as a header may need to accommodate that when accessing the data through the data member.