I've started learning Linux programming among C and I encountered the following:
time_t now;
struct tm *local_time;
now = time(NULL);
local_time = localtime(&now);
The function localtime, which is part f the Linux API, accepts a pointer to time_t which is fine, but why does it return a pointer to tm struct?
My question is how does the tm struct being managed after it's initialisation?
if localtime allocated the struct statically it can't guarantee that the struct won't be overwritten as the program proceeding and if the tm struct is dynamically allocated then the programmer must call free the struct is no longer needed.
So what is the correct phase for C function that returns a pointer?
Thanks!
According to the manpage for localtime (bold and italics added for clarity):
The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The localtime_r() function does the same, but stores the data in a user-supplied struct. It need not set tzname, timezone, and daylight.
The bold part indicates that the return value behaves exactly as you guess, where a subsequent call might overwrite the previously-returned struct.
You either need to immediately cache the resulting struct or utilize the function mentioned in the italicized portion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With