One problem which I see in your code is that you access memory beyond the array. If you add two indices, you have to make sure that they "wrap ...
stackoverflow.com