MISRA Discussion Forums
semantic type checks - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.10 The essential type model (https://forum.misra.org.uk/forumdisplay.php?fid=165)
+---- Thread: semantic type checks (/showthread.php?tid=1425)



semantic type checks - danielmarjamaki - 22-05-2018

It is written in the misra document that the operands for > must be unsigned. In my humble opinion, you are missing something. Semantic type checks are not particularly safe, I claim they are dangerous.

Sanitizers, static analyzers and compilers are checking that the operands are not negative. By following this MISRA advice, these checks are "disabled".

Simple example code:
Code:
int32_t foo(void)
{
    int32_t x = -1;
    return x >> 3;
}

This is UB so the static analyzers/compilers/sanitizers will write a warning. For instance 1 tool writes:
Shifting a negative value is technically undefined behaviour

If MISRA is enforced then the operand must be casted to unsigned somewhere, the developer might change it to:
Code:
int32_t foo(void)
{
    int32_t x = -1;
    return (uint32_t)x >> 3;
}

Now the tools don't complain. The bug is hidden.

To help prevent some such damage, I have thought about a rule that makes such casts illegal, when there is loss of precision or loss of sign in explicit casts. But that is used by intention sometimes, as far as I know, so it might be noisy.


Re: semantic type checks - misra-c - 04-10-2018

Note: The MISRA-C 2012 guidelines do not tell you to "add the cast". Without the cast the user would definitely get a MISRA C violation and possibly a compiler warning. In both cases the user might then choose to add a cast to remove the warning.

In adding a cast the user has signified that he has considered what happens when the cast is applied.

Aside: The example has a 10.3 violation between the return type of uint32_t and the expected type of int32_t.