Thursday, March 1, 2012

Can you find the bug? Part One

With this year being a leap year and all, I've been looking at a couple of famous leap year (and general date) blunders tonight. It's quite embarassing how often we as programmers get date arithmetic wrong. I've read about a couple tonight, not the least being a bug in old apache commons-net which made files created on 29 Feb dissapear from FTP file listings!
Anyway, if I'm honest, I'm sure there is code out there that I've written that could also potentially have leap year problems. You need to be wary when working with dates. For example, doing something like:
    Date lastYear = new Date(today.getYear() - 1, today.getMonth(), today.getDay())
for working out a date a year back could be potentially problematic. So we should just be always wary of date arithmetic when writing such code.
In any case, this post has got another point: I want to start a sort of "game" or "tradition" on the blog if you will. I want to call it: "Can you find the bug?". The idea being, that whenever we come across a piece of code with a subtle, or huge, or blaringly obvious bug in our daily lives, we share it, and "challenge" the others to see if they can find it. Not with the idea of mocking the code or the author, but with the point of learning. And also testing our bug-catching eyes. Because there's no better way to learn than to analyse code that is actually running in the wild. Kind of like our own DailyWTF - but a bit more focused, and perhaps relevant.
Now we shouldn't be shy, it could be code we wrote ourselves (I know I've had a couple epic ones!).
Now today, I've got a doozy for you guys. I'm not going to give you the full story just yet... but let's just say this code comes from a VERY prominent IT company, and this was code that actually shipped in a product that this company delivered and was used by millions of people all over the world. This piece of code also made the product in question completely and utterly useless on a certain day. I want you guys to find out what the bug, and that day is. Bonus points if you can tell me the company/product in question. This bug is not limited to a certain, specific, once off day - it will happen on any day that fits a certain pattern.
The original code was C, and for the purposes of this excercise I took the relevant part and transcribed it into python. Here it is:

I've verified that the general case of the bug exists by running it myself. You can run the script with "python ". The point of the code was apparently to find out the year,month,day that a given value representing "days since 1980" falls in. I've just transcribed the relevant parts. Hope I didn't screw it up!
So, see if you can spot the bug. Additionally, what would you do to fix it?
Hope you guys enjoy! And if this works out to be a fun exercise we'll do it again!

No comments:

Post a Comment