PORTING.VAR.EFFECTS
Variable used twice in one expression where one usage is subject to side-effects
The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.VAR.EFFECTS checker detects situations in which a variable is used twice in one expression, and at least one usage is subject to side-effects.
This checker detects violations of the MISRA C 2004 standard, rule 12.2, and of the MISRA C++ 2008 standard, rule 5-0-1.
Vulnerability and risk
Order of evaluation is not defined by the C standard, so using a syntax shortcut can have significant operational impact when code is ported between different compilers. This checker detects situations in which assignment is made as part of a function call's parameter list. This assignment isn't always guaranteed to happen before the function call is made, resulting in different results on different platforms.
Mitigation and prevention
Don't use syntax shortcuts, especially when there's a chance of the code being ported to a different compiler.
Vulnerable code example
void foo(int m) { printf("Foo called with %d\n", m); }
void bar(int m) { printf("Bar called with %d\b", m); }
void laab()
{
int m = 0;
void (*fp[3])(int);
fp[0] = foo;
fp[1] = bar;
(*fp[++m])(++m); // PORTING.VAR.EFFECTS
}
Depending on the compiler in use, either function 'foo' or 'bar' might get called, although probably always with a value of 2 for 'm'.
Fixed code example
void foo(int m) { printf("Foo called with %d\n", m); }
void bar(int m) { pritnf("Bar called with %d\b", m); }
void laab(int fn)
{
int m = 0;
void (*fp[3])(int);
fp[0] = foo;
fp[1] = bar;
(*fp[fn])(++m);
}
In the fixed code, there's no ambiguity in the expression. We know exactly which function will be called, and 'm' is always 1 as expected.