Exercise 39: Bug?

I think I have found a bug in string_algos.c. It’s in StringScanner_scan, line 124:

scan->hlen -= found_at - scan->nlen;

If you print out scan->hlen after each search in string_algos_tests.c, you get weird numbers that just happen to not break the test cases.

The problem is that scan->hlen is already the remaining length in the current iteration, so we can’t just subtract the found index (that relates to the whole haystack) and the length of the needle (in which case it’d have to be scan->hlen -= found_at + scan->nlen, too).

I’ve changed it to

scan->hlen = blength(scan->in) - found_at - scan->nlen;

and the tests keep running and the intermediate states of scan->hlen are now correct.

A free service run by Zed A. Shaw for learncodethehardway.org.