cembeddedstructure

PC-LINT Warning while Copying Struct into array in C


This is my first question on Stack Exchange so be with me. In one of my embedded C projects, I am trying to copy a portion of structure data into an array. Ex:

typedef struct
{
  uint16_t Length_ui16;
  uint8_t  Message_Id_ui8;
  uint8_t  SensorPosition_ui8;
  uint8_t  SenType_ui8a[9];
  uint8_t  SenArticleNo_ui8a[9];
  uint8_t  SenSerialNo_ui8a[9];
  uint8_t  SenSoftVer_ui8a[6];
}data;

memcpy(destArr_ui8, &data.SensorPosition_ui8, 34);      

Explanation: I am trying to copy data from SensorPosition onwards (34 bytes). NOTE: structure padding and destArr size is already taken into consideration Code is working as per my expectations. But my PC-LINT got with me on this.

PC-LINT Warning 662: Possible creation of out-of-bounds pointer (33 beyond end of data) by operator '['

My analysis is that PC_LINT thinks that the source is just a single byte variable (SensorPosition ), so giving 33 bytes outbound warning.

So, the real question is that,

  1. Is there any other elegant or commonly used method which is satisfy PC_LINT also to achieve the same thing.
  2. If, no than how do I change my code to satisfy the PC_LINT on this.

Solution

  • If I understand correctly, the "payload" of the data structure needs to be copied to a byte array.

    The following creates a pointer to the payload viewed as bytes and calculates the payload size to do the copying:

      const uint8_t *Payload = (const uint8_t *)data + offsetof(data, SensorPosition_ui8);
      size_t PayloadSize = offsetof(data, SenSoftVer_ui8a) + sizeof(data.SenSoftVer_ui8a) - offsetof(data, SensorPosition_ui8);
      memcpy(destArr_ui8, Payload, PayloadSize);
    

    Notice that this calculation of PayloadSize excludes any padding which the compiler may have inserted at the end of the structure. It is highly unlikely that padding will be inserted between members in this structure. To make absolutely sure, a static assertion may be added to check that the expression for PayloadSize is actually 34.

    If it has already been checked that there is no padding (between or after members) in the struct, then the calculation of PayloadSize can be simplified to sizeof(data) - offsetof(data, SensorPosition_ui8).