Page 1 of 1

Insidious bug in Count() in backend.c

PostPosted: 21 Nov 2015, 20:10
by beneficii
In Count() in backend.c, there is a bug that can result in an increment to an index in an array that is out-of-range. The code should be changed as follows:

From:

Code: Select all
p = board[r][f];
pCnt[p]++;


To:

Code: Select all
p = board[r][f];
if(p <= EmptySquare) pCnt[p]++;


The reason for this is that pCnt[] as called by Adjudicate(), also in backend.c, takes a static array that is declared as nr[EmptySquare+1]. Therefore, if the loop in Count() comes across a square with a higher index than EmptySquare, such as DarkSquare, then the increment is out-of-range.

In debugging with a chess variant that does uses squares with a higher index than EmptySquare (specifically, I added one called Impassable, which was DarkSquare +1 and EmptySquare + 2), the stack around the variable staleB in Adjudicate() kept getting corrupted. In extensive debugging where I kept a watch on the stack around that variable, I found that the code above, without checking that p <= EmptySquare, was the culprit. Making the change by adding the check fixed the problem.

Re: Insidious bug in Count() in backend.c

PostPosted: 25 Nov 2015, 17:43
by H.G.Muller
Thank you for spotting this. This counting code is from before the introduction of dark squares, and the latter was never really tested thoroughly.