C struct initialization and strptime bug

I wrote some code to use strptime to parse a human-readable time string into a struct tm and I had a bug where the struct had the hour one hour in the past, which suggested a daylight savings time (dst) problem.
After puzzling over this for a bit, I found the answer.

It turns out that contrary to what I and several others had remembered, there is no guarantee
in C that it will initialize stack structs and arrays to zeros and then on
top of that strptime has this lovely behavior that not only is it using the
struct for output, it’s using it for input as well. Specifically, it looks
at the tm\_isdst field to see if you want a dst time or not and since my
struct was initialized to garbage…. it could go either way. Solution is to
say struct tm time_struct = { 0 }; or use memset, as long as the struct is
zero-filled – I chose the former, because it is more concise.

I’m told that Java zero-fills, which perhaps has a minor performance penalty, but at least it prevents this sort of bug. I’ll trade speed of execution for something that is more likely to be correct and thus not require debugging.

Take Charge and Initialize Your Own Data

Leave a Reply

Your email address will not be published. Required fields are marked *