In order for this code to run properly, memset must be used. Why is that?
struct tm temp;
memset(&temp, 0, sizeof(struct tm));
strptime(str.c_str(), "%d-%m-%Y", &temp);
Why this is not enough?
struct tm temp;
strptime(str.c_str(), "%d-%m-%Y", &temp);
Thanks a lot.
Because of this little snippet in the strptime
specification (my emphasis):
values for the appropriate
tm
structure members are set to values corresponding to the locale information.
In other words, it doesn't necessarily set all the fields of a tm
structure, so you initialise everything to zeros first. Otherwise, being a local variable, it's likely to have arbitrary information in all its fields before parsing the time string (and after, unless you're explicitly parsing an appropriate item).
One reason it does this (skipping fields you don't explicitly parse) is because you may already have a tm
set up and you only want to change certain fields (for example, using time()
and localtime()
to get the tm
for today, and then parsing 5pm to get that specific time for today).
There's a good chance that, if you're only going to be looking at the fields you parsed, you won't have to worry about zeroing first. But there may also be the possibility that whoever wrote your strptime
implementation was "too clever", and decided they could post-massage the data to fix problems. For example, if you have 26:00:00
as the time, and you parse the date for March 1
, it may adjust it to March 2, 02:00:00
.
I'm not saying that's likely (or even allowed by the specifications) but, given the minimal cost of zeroing the structure before-hand, I'd probably prefer to be safe. Especially since there are many people out there who are "too clever" :-)