I'm sure you've had this experience: Part of your program isn't working as you expect, so you make the obvious change--and now it fails in a different way. Soon, you realize what you did, and change it again; but again all you've done is substitute one bug for another.
It took me years, but I finally realized that when this happens, it usually means that I don't really understand the problem as well as I think I do. The right thing to do in such a situation is to take a step back and rethink the problem from first principles.
In my 1988 book C Traps and Pitfalls, I quoted from the construction manual for a harpsichord. The author, David Way, may never have written a computer program, but he knew what he was talking about:
"Thinking" is the cause of all error: I can prove this by the fact that whoever makes a mistake always says, "Oh, but I thought..." Never mind this kind of thinking-- before you glue anything together you must know...
I've heard the sad story so many times: "Last night I did so and so, and this morning when I looked at it..."
Dear builder, if you had looked at it last night you could still have taken it apart and put things right. ... If I can believe my telephone calls, most mistakes are made the last thing before you go to bed. So go to bed before you do the last thing.
The last two paragraphs allude to a second source of error, namely that you may have been thinking about your problem for so long that you've gotten tired. Fortunately, in either case, the solution is the same: Take a step back and look at it again with fresh eyes.