Home

Programs with Proofs: Counting Occurrences in an Array

Method of Proving

This is a program which also contains annotations to help prove its correctness using the Frama-C software.

The annotations specify various properties for a method like the pre-condition, post-condition, assertions, states modified, loop-invariants and loop-variants. They are also used to define other artifacts to ease specification/proving like predicates, logic functions, axioms and lemmas. These annotations are provided inside code-comments of the form /*@ ... */ and //@ ....

Frama-C with its WP plugin works with external provers like Alt-Ergo and CVC4 to automatically prove these specified properties. The WP plugin internally works based on the Weakest Precondition calculus. You can read more about this plugin's usage and meaning of the annotations in this tutorial.

The programs provided here have been proved using these versions of the tools: Frama-C (contains WP plugin) 21.1, Alt-Ergo 2.3.1 and CVC4 1.6. The system is x86_64 running Debian 10 Linux.

In addition to proving the specified properties, we will also be checking for other issues like overflows via another Frama-C plugin called RTE (by using option -wp-rte).

Command to prove this program:
frama-c -wp -wp-prover cvc4 -wp-rte filename.c

Counting Occurrences in an Array


/* Method occurs() counts the number of times x occurs in array a[] of n elements. */

typedef unsigned int uint;

/*@
  axiomatic axm
  {
    // Define the logical-function count() as returning the number of occurences of x
    // among first n elements of array a[].
    logic uint count(int *a, uint n, int x)
      reads a[0..n-1];

    axiom base:
      \forall int *a, x; count(a, (uint)0, x) == 0;

    axiom recursion:
      \forall int *a, x, uint n; n >= 1 ==>
      (count(a, n, x) == count(a, (uint)(n-1), x) + ((a[n-1]==x) ? 1 : 0));
  }
 */

/*@
  requires \valid(a + (0..n-1));
  assigns \nothing;
  ensures \result == count(a, n, x);
 */
uint occurs(int *a, uint n, int x)
{
  uint i, c;

  i = 0;
  c = 0;

  /*@
    loop assigns i, c;
    loop invariant c == count(a, i, x);
    loop invariant 0 <= i <= n;
    loop variant n - i;
   */
  while(i < n)
  {
    if(a[i] == x)
      c = c + 1;

    i = i + 1;
  }

  return c;
}