Search code examples
cpointersnull-pointermisra

Null pointer issue


I am facing a MISRA C 2004 violation of rule 1.2 "likely use of null pointer. The code that I am using is as below:

tm_uint8* diagBuf = 0u;
diagBuf[0] = diagBuf[0] + 0x40u; 
diagBuf[2] = 0x01u;
diagBuf[0] = diagBuf[0] + 0x40u;
diagBuf[2] = 0x01u;

This is just a part of the code that is indicated above. some of the statements have "IF" conditions.

Can some one point out why I get the MISRA Violation.?


Solution

  • According to the 1999 C standard, Section 6.3.2 "Pointers", para 3

    An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

    (Note I've removed cross reference at the end of the first sentence in the above to a footnote which explains that NULL is defined in <stddef.h> and other headers as a null pointer constant).

    This means that

    tm_uint8* diagBuf = 0u;
    

    initialises diagBuf using a null pointer constant, since 0u is an integer constant expression with value zero. Accordingly, diagBuf is initialised as a null pointer.

    Furthermore the following statements

    diagBuf[0] = diagBuf[0] + 0x40u; 
    diagBuf[2] = 0x01u;
    

    both dereference a null pointer. That is undefined behaviour according to C standards.

    The reported Misra violation is therefore completely correct.

    The circumstances in which such code would be acceptable (e.g. it would be possible to write a justification for an exemption from the Misra rule, and get that approved in context of the system development) are very limited in practice.