Gmtime changes two pointers at the same time

I have this code:

time_t tt = time(NULL); tm* currentTime = gmtime(&tt); tm* storedTime = gmtime(&m_time); 

Where m_time is the time_t dataset set at build time. When I set storedTime with this data element, the current time gets the same value, as if both tm pointers were pointing to the same variable. Is this expected behavior? How could I separate tm structs for time comparison?

thanks

+4
source share
2 answers

From the gmtime documentation:

This structure is statically distributed and shared by gmtime and localtime. Each time one of these functions is called, the contents of this structure are overwritten .

Use this code to create a copy:

 time_t tt = time(NULL); tm currentTime = *gmtime(&tt); tm storedTime = *gmtime(&m_time); 

(the meaning of the pointer here is equivalent to memcpy(¤tTime, gmtime(&tt), sizeof(tm)) )

+5
source

They probably return the address of a local static variable. For instance.

 struct tm *gmtime(struct time_t *tt) { static struct tm local_tm; /* do work */ return &local_tm; } 

Looking at man pages over the Internet (I google "man gmtime"), this is a common topic that it is not a re-entry function and can even share the return value with other functions:

POSIX.1-2001 says: "Asctime (), ctime (), gmtime () and localtime () functions must return values ​​in one of two static objects: a broken time structure and an array of type char. The execution of any functions can overwrite information, returned to any of these objects by any of the other functions. "

+1
source

Source: https://habr.com/ru/post/1411722/


All Articles