[SystemSafety] Subversive C programs for mockery of static analysis tools ... on a bad day ; -)

Olwen Morgan olwen at phaedsys.com
Sat Dec 1 14:22:33 CET 2018


One of my cooked-up subversive programs was cocked-up. Here is the 
corrected version of cimplex-d-0004.c:


#include <stdio.h>

static int j = 0;

int incr(int n) { return j = n+1; }

int main(void)
{
     char a[2] = {'R', 'R'};
     int  i    = 0;

     char b[2] = {'R', 'R'};

     a[i] = (++i, 'L');
     b[j] = (incr(j), 'L');

     printf("\nEvaluation of = in \"a[i] = (++i, 'L');\" is %c%c\n", 
a[0], a[1]);
     printf("\nEvaluation of = in \"b[j] = (incr(j), 'L');\" is %c%c\n", 
b[0], b[1]);

     return 0;

}


The previous incorrect version had incr() defined as a purely 
applicative function that did not preserve state from an earlier call. 
Hence, the last output line from the incorrect program reported the 
order of evaluation incorrectly. For the above program both gcc and 
clang report the order of evaluation of the = operator as RL. cppcheck 
reports only the double side effect in the assignment to a[i]. Since the 
incorrect version appeared to show RL evaluation in one context and LR 
in another, I'm more than a little relieved that this is not the case.

Rather neatly, this illustrates the difficulty of writing 
implementation-dependent programs when you have spent a long time with a 
coding mind-set aimed at avoiding implementation-dependency. The 
thinking-fast part of the cognitive process simply follows habitual 
patterns not noticing that the results don't do the required job.


Olwen







More information about the systemsafety mailing list