It seems that off-by-one errors are one of the most (if not the most) common programming errors (see https://softwareengineering.stackexchange.com/questions/109/what-are-common-mistakes-in-coding, and conventional wisdom).What is the reason these are so common, is it something to do with how the human brain works?What can we do to prevent falling prey to the off by one errors?
Why are off by one errors so common and what can we do to prevent them?
coding;bug
It sort of is something to do with how the human brain works.  We're wired to be good enough for tasks that don't usually require engineering-grade precision.  There's a reason why the cases we have the most trouble dealing with are called edge cases.Probably the best way to avoid off-by-one errors is encapsulation.  For example, instead of using a for loop that iterates a collection by index (from 0 to count - 1), use a for-each style loop with all the logic of where to stop built into the enumerator.  That way you only have to get the bounds right once, when writing the enumerator, instead of every time you loop over the collection.