Evgeney Knyazhev said:
Ben, i respect, & am thankful for your code inspection + your
suggestion, but i did check it many times & everything has been
ok. that logical scheme can fail, if you send bad value of 'end'. if
'end' equals length of array than stuff runs trouble - free.
How did you check it? Did you actually do any of (a), (b) or (c) that I
suggested or did you just assume that it must be right because you ran
the program a few times and you got the output you expected?
If you do nothing else, please add #include <assert.h> at the top of the
file and, just before the code that accesses 'a[child+1]' put:
assert(child + 1 < 100000);
'a' points to an array of length 100000 so if this assertion fails you
will know that the code has a bug. If I do that using exactly the code
you posted I see:
(C) 2013 Evgeney Knyazhev.
Start No-IF heapsort
e: e.cc:77: int siftDown(int64_t*, int, int): Assertion `child + 1 < 100000' failed.
Aborted
Of course you could just think about the program: main calls heapSort
with end==100000. That calls Heapify with end==100000 which in turn
calls siftDown with root==49999 and end==100000. siftDown starts:
int child;
int count = 0;
int64_t dv;
child = root << 1;
child++;
At this point child == 99999, so the loop is entered:
while(child < end)
{
dv = (child + 1 < end);
dv = (a[child] < a[child+1]) * dv;
At this point child+1 is not a valid index for the pointer 'a'.
<snip>