Alexander Shaw
Alexander Shaw

Reputation: 69

How to use mktime() without changing the original tm struct?

I've recently came up with a problem using the code:

time_t today_t;
time(&today_t);
tm *today = localtime(&today_t);

time_t tomorrow_t = mktime(today);
tomorrow_t += 86400;
tm *tomorrow = localtime(&tomorrow_t);

The problem is that my today object changes right after i use localtime(&tomorrow_t) to create tomorrow object, and values of both objects become equal. I don't really understand this behavior. Any help, please?

Upvotes: 0

Views: 1179

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263267

Quoting the Linux man page for the localtime function:

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.

So if you call localtime() twice, it will return the same pointer value each time, overwriting it with the new value. today is a struct tm* pointer, which you own; *today is a struct tm object, which is owned by the C library.

Either copy the structure (not the pointer) to another struct tm object after the call or use localtime_r which writes to a structure that you supply. (localtime_r is not 100% portable; it's defined by POSIX, but not by the ISO C standard.)

Upvotes: 0

Craig Estey
Craig Estey

Reputation: 33601

localtime uses a single static variable for the tm struct and returns a pointer to it. Thus, today and tomorrow will have the same address.

There is a reentrant version localtime_r that takes a second argument where you can specify where the struct data is placed.

Upvotes: 3

Related Questions