0

I have to send UDP packets in a vehicle's LAN. The UDP packet consists of 5 fields:

field_1: 4 bytes uint32_t
field_2: 1 byte  uint8_t
field_3: 1 byte  uint8_t
field_3: 2 bytes uint16_t
field_4: 20 bytes 5*float

I wonder if doing memcpy in a buffer of chars is MISRA C compliant, the code is here:

uint32_t field_1    = 25;
uint8_t  field_2    = 34;
uint8_t  field_3    = 1;
uint16_t field_4    = 234;
float   field_5[5]  = {1,2,3,4,5};


/* Allocate memory for the buffer*/
int l_buffLen = sizeof(uint32_t)
                + sizeof(uint8_t)
                + sizeof(uint8_t)
                + sizeof(uint16_t)
                + 5*sizeof(float);

char  buffer[l_buffLen];


/* Copy data to the buffer */
int idx = 0;
memcpy(&buffer[idx],&field_1,sizeof(uint32_t)); 

idx+=sizeof(uintt32_t);
memcpy(&buffer[idx],&field_2,sizeof(uint8_t));   

idx+=sizeof(uint8_t);
memcpy(&buffer[idx],&field_3,sizeof(uint8_t));   

idx+=sizeof(uint8_t);
memcpy(&buffer[idx],&field_4,sizeof(uint16_t));   

idx += sizeof(uint16_t);
memcpy(&buffer[idx],field_5,sizeof(float)*5);          
Andrew
  • 2,046
  • 1
  • 24
  • 37
ignatius
  • 189
  • 2
  • 14
  • Do sender and receiver of those packets share the same architecture and the same internal representation of a `float`? – Bob__ Jul 31 '18 at 09:00
  • 1
    You're repeating the types of each field and the array size multiple times, that's not good from a code quality perspective, which I presume is important since you care about MISRA. Why not write `sizeof(field_1)` instead of `sizeof(uint32_t)` – rustyx Jul 31 '18 at 09:09
  • @Bob__ there are two systems that act as senders and receivers. One system is Linux and the other is Windows – ignatius Jul 31 '18 at 09:57
  • @rustyx it's a good advice! – ignatius Jul 31 '18 at 09:57
  • Using `char` for a generic data buffer is certainly not MISRA compliant. MISRA does not allow `char` for integer arithmetic, but only for strings. You need to switch to `uint8_t` instead. Other than that, using memcpy is fine, as it avoids a whole lot of problems with alignment, strict aliasing etc. – Lundin Aug 06 '18 at 09:57

2 Answers2

2

MISRA C does not prohibit the use of memcpy()

MISRA C:2012 Amendment 1 (free download available) provides some guidance on using memcpy() to help avoid some of the undefined/unspecified behaviour endemic in the C Standard - there are plenty of tools available to help you in the analysis of your code

Note: See profile for disclaimer

Andrew
  • 2,046
  • 1
  • 24
  • 37
-2

The right tool for the job of copying a known size block of bytes is memcpy(). If MISRA dings you for that, then MISRA isn't worth the electrons it's printed with.

mlp
  • 809
  • 7
  • 21