Search code examples
cstructurevoid-pointersmemsetmisra

How to properly solve memset() function MISRA errors in C?


I have written a simple function to initialise the structure values using memset(). These are the code I have written in C language.

myfile.h

typedef struct{
 bool flag;
 bool check;
 int val_1;
 int val_2;
} MY_STRUCT;

myfile.c

static MY_STRUCT mystruct;

void Test()
{
  memset(&mystruct, 0, sizeof(MY_STRUCT)); 
}

When i run MISRA , i am getting this kind of error

The return value of non-void function 'memset' shall be used

I have tried to fix this warning using below method

(void)memset(&mystruct, 0, sizeof(MY_STRUCT)); 

But unfortunately, i am getting 2 new warnings

Cast between types that are not both pointers or not pointers

object of pointer type 'void*' cast to unrelated type 'void'

Anybody suggest how to fix this warning while using memset() function ? Also please explain to avoid such warnings in future.


Solution

  • You need to understand the rationale behind the rules if you are to work with MISRA-C.

    The first problem should indeed be solved by casting the result to (void). The reason for this rule is to enforce error checking of returned values from functions, which doesn't apply in this case, since memset's admittedly weird API is simply returning the first parameter.

    The rest of the warnings you get seem to be false positives by your tool. It is compliant to explicitly cast the return value of any function to (void), see MISRA C:2012 17.7.

    A work-around isn't required for MISRA compliance, though if you just wish to silence the tool, then this would be MISRA compliant too, and equivalent to memset:

    mystruct = (struct MY_STRUCT){ 0u };