I am using standard memcpy function which declared in string.h file thus:
extern void * memcpy(void *, const void *, size_t);
Case 1 : My code is compiled without any error or warnings.
const uint8_t *buff = (uint8_t*)Getbuff();
uint8_t data[3] = {0};
memcpy((void*)data,(const void*)(buff+2),3U);
After checking MISRA C:2012 I am getting following MISRA error:
performing pointer arithmetic via addition [MISRA 2012 Rule 18.4, advisory]
memcpy((void*)data,(const void*)(buff+2),3U);
Case 2 : If I fix MISRA error in Case 1 thus:
const uint8_t *buff = (uint8_t*)Getbuff();
uint8_t data[3] = {0};
memcpy((void*)data,(const void*)(buff[2]),3U);
I am getting compile time warning and a different MISRA error.
Compile time warning :
cast to pointer from integer of different size
MISRA error:
explicit cast from
'const UINT8'
(aka'const unsigned char'
) to'const void *'
[MISRA 2012 Rule 11.6, required]memcpy((void*)data,(const void*)(buffer[2]),3U);
Just;
memcpy( data, &buff[2], 3u ) ;
Both the pointer arithmetic and casts are unnecessary and contrary to MISRA rules.
To cast to a void*
rather misunderstands the purpose of a void-pointer, and casting in general can suppress essential warnings that the compiler might otherwise issue. The resulting de-clutter makes the code much easier to read and MISRA compliant.
Your second case was also semantically incorrect, and would not have resulted in correct behaviour - warnings are not always just warnings; often they indicate semantic errors. For the compiler "error" just means "cannot be compiled" (syntactic error); a semantic error is one where the code does not do what was intended.