File tree 2 files changed +49
-0
lines changed
regression/contracts/loop_contracts_binary_search 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include <assert.h>
2
+ #include <stdlib.h>
3
+ #include <stdbool.h>
4
+
5
+ #define NOT_FOUND (-1)
6
+
7
+ int binary_search (int val , int * buf , int size )
8
+ {
9
+ if (size <= 0 || buf == NULL ) return NOT_FOUND ;
10
+
11
+ long lb = 0 , ub = size - 1 ;
12
+ long mid = (lb + ub ) / 2 ;
13
+
14
+ while (lb <= ub )
15
+ __CPROVER_loop_invariant (0L <= lb && lb - 1L <= ub && ub < size )
16
+ __CPROVER_loop_invariant (mid == (lb + ub ) / 2L )
17
+ __CPROVER_decreases (ub - lb )
18
+ {
19
+ if (buf [mid ] == val ) break ;
20
+ if (buf [mid ] < val )
21
+ lb = mid + 1 ;
22
+ else
23
+ ub = mid - 1 ;
24
+ mid = (lb + ub ) / 2 ;
25
+ }
26
+ return lb > ub ? NOT_FOUND : mid ;
27
+ }
28
+
29
+ int main () {
30
+ int val , size ;
31
+ int * buf = size >= 0 ? malloc (size * sizeof (int )) : NULL ;
32
+
33
+ int idx = binary_search (val , buf , size );
34
+ if (idx != NOT_FOUND )
35
+ assert (buf [idx ] == val );
36
+ }
Original file line number Diff line number Diff line change
1
+ CORE
2
+ main.c
3
+ --apply-loop-contracts _ --pointer-check --bounds-check --signed-overflow-check
4
+ ^EXIT=0$
5
+ ^SIGNAL=0$
6
+ ^\[binary_search.1\] .* Check loop invariant before entry: SUCCESS$
7
+ ^\[binary_search.2\] .* Check that loop invariant is preserved: SUCCESS$
8
+ ^\[binary_search.3\] .* Check decreases clause on loop iteration: SUCCESS$
9
+ ^\[main.assertion.1\] .* assertion buf\[idx\] == val: SUCCESS$
10
+ ^VERIFICATION SUCCESSFUL$
11
+ --
12
+ --
13
+ This test case verifies memory safety and termination of a binary search implementation.
You can’t perform that action at this time.
0 commit comments