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.
CodePudding user response:
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 };
CodePudding user response:
The return value of the memset
function is a void*
pointer, which is a copy of the passed first parameter (dest
). In your case, that is the address of an actual variable, so it cannot feasibly be NULL
; thus, comparing the returned value to NULL
would most likely prevent the MISRA warning (but that test should really never fail):
if (!memset(&mystruct, 0, sizeof(MY_STRUCT))) {
(void)fputs("I'm sorry, but an impossible error has occurred!\n", stderr);
}
CodePudding user response:
The cited code:
static MY_STRUCT mystruct;
void Test()
{
memset(&mystruct, 0, sizeof(MY_STRUCT));
}
Is a violation of MISRA C:2012 Required Rule 17.7 which states, unambiguously, that The value returned by a function having non-void return type shall be used.
memset()
returns a void*
and therefore to comply with Rule 17.7 it must be used or as suggested by the Rule, cast to void
.
While in the specific case of memset()
it could be argued that the return value is pointless the language is the language and the MISRA Rule does not have an exception.
Adding a cast to (void)
should be no overhead... but if you are specially concerned, you could always deviate the Rule instead.