Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this?

Moderators: misra-c, david ward

Post Reply
guru72
Posts: 1
Joined: Tue Sep 18, 2018 6:07 pm
Company: Qualcomm

Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this?

Post by guru72 » Wed Sep 19, 2018 6:30 pm

Hello,
I have the following piece of code for which I get a MISRA Rule 2.1 error. I am considering a deviation for this - All possible error status from a function call can be checked even if the function does not return all possible error statuses. Can you please provide feedback on if this is a reasonable deviation?

(Btw, this is my first post - please feel free to let me know if this is outside the scope here)

Example:

Code: Select all

#include "stdafx.h"
typedef enum ErrStatus {
    Success = 0,
    Err_1,
    Err_2
} ErrStatus;

ErrStatus f(int x) {
    if (x < 0) {
        return Err_1;
    }
    else
    {
        return Success;
    }
}

    int main()
    {
        ErrStatus x = f(5);
        switch (x)
        {
        case Err_1:
            printf("err 1"); break;
        case Err_2:
            printf("err 2 "); break;  /* Is this dead code ? */
        default:
            printf("Success"); break;
        }
    }

misra-c
Posts: 548
Joined: Thu Jan 05, 2006 1:11 pm

Re: Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this?

Post by misra-c » Thu Oct 04, 2018 10:50 am

The example correctly produces a rule 2.1 violation as it can be determined that "x" will never have the value of "Err_2". A deeper analysis tool might also give a violation on "Err_1" since the value returned by f(5) will always have the value of "Success".

The proposed deviation is not sufficent as stated as there is nothing to prevent a compiler from "optimising" away the code for "Err_1" and "Err_2" cases. Instead the switch chooser should be accessed by means of a volatile qualified lvalue. For example

Code: Select all

switch ( *( volatile ErrStatus * ) &x )
This makes the code compliant with this rule AND prevents the case branches being optimised away by the compiler.

When writing a deviation you should read the MISRA Compliance document which can be found at https://tinyurl.com/MisraCompliance.
With respect to this question you should consider the advice given in the MISRA C:2004 14.1 B.1 permit of the "MISRA C 2004 Permits" document, which can be found at https://tinyurl.com/MisraPermits2004. This document was written for MISRA-C:2004, but advice given in this permit is relevant to MISRA C:2012.
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “8.2 Unused code”