Applied Deliberation

Assorted Adventures of Sampsa Kiiskinen

Exercise on Preventive Analysis

Consider a program that is in charge of controlling heavy machinery for analyzing component materials.

It is accessed through a procedure, which takes a set of elements and produces a result based on all the possible unordered pairs that can be formed from them.


For example the following elements

Number Element
1 Hg
2 Ba
3 Ca
4 Cu
5 O

produce the following pairs,

Number One Other
1 Hg Ba
2 Hg Ca
3 Hg Cu
4 Hg O
5 Ba Ca
6 Ba Cu
7 Ba O
8 Ca Cu
9 Ca O
10 Cu O

where the rows and the columns are in no particular order.


The relevant part of the source code is shown below.


The publicly visible analyze procedure checks its arguments and delegates the hard work to analyze_for_real, which then writes its result into the result pointer.

The set of interest is represented as an array of unique elements and the element count is stored in a variable of type size_t, as it should. However the amount of pairs may exceed the amount of elements. That is a problem, because size_t may be the largest unsigned integer type available, in which case the amount of pairs will not fit into any kind of variable. The solution is to limit the amount of elements to COUNT_MAX.

The limit is currently set so low that nothing unsafe may happen. Unfortunately nothing useful may happen either.


Your job is to find the highest possible COUNT_MAX that does not cause an overflow during pair formation.

The catch is that COUNT_MAX must be a compile-time constant. Therefore it may only depend on

instead of count.