为何两段仅tm初始化不同的C++代码本地一致但Kattis判题结果不同?
tm Struct Works on Kattis Great question! Let's break down why this tiny initialization difference leads to different results on the Kattis judge, even though both code versions work fine locally.
The Root Cause: Uninitialized Memory vs. Value Initialization
When you write:
struct tm time;
You’re declaring a tm struct but leaving all its members uninitialized. In C++, local stack variables don’t get automatically reset—they hold whatever random "garbage" data was left in that memory spot from previous operations. The tm struct has more members than just the day/month/year you probably set: things like tm_hour, tm_min, tm_sec, and tm_isdst (daylight saving time flag) all exist here, and they’ll have unpredictable values if you don’t initialize them.
On the flip side:
tm time = {};
This uses value initialization, which sets every member of the struct to a safe default (0 for integer types, null for pointers, etc.). Every part of the tm struct starts with a predictable, non-random value, even if you don’t explicitly set it later.
Why This Breaks mktime (And Your Kattis Submission)
The datum problem almost certainly relies on mktime to convert your tm struct into a timestamp, then uses that to calculate the weekday. Here’s the critical detail: mktime doesn’t ignore uninitialized members—it uses every single one of them to compute the final time.
- Local luck: On your machine, the garbage values in the uninitialized
tmstruct might have happened to be 0 (or values that don’t mess up the weekday calculation). For example, iftm_houris 0,tm_minis 0, andtm_isdstis 0 (no daylight saving), the math still checks out. - Kattis environment differences: On the judge’s servers, those garbage values are different. Maybe
tm_isdstis a random non-zero value, tellingmktimeto assume daylight saving is active (shifting the time by an hour). Ortm_houris a huge number that rolls over into the next day—suddenly the computed weekday is wrong, and your submission fails.
Why Your Second Code Works
By zero-initializing the tm struct with = {}, you eliminate the randomness. All unused members start at safe defaults, so mktime can reliably compute the correct time based on the day/month/year you set, without being thrown off by garbage data.
Even if you think you’re setting every necessary member, initializing structs like tm is a critical habit to avoid environment-dependent bugs like this.
内容的提问来源于stack exchange,提问作者A. Park

