Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

function - How is the result struct of localtime allocated in C?

I was playing with the time.h file in C that helps us with time/day functions.

I came across:

struct tm * _Cdecl localtime(const time_t *__timer);

...which seems to return a pointer to tm struct. I have found that return by address is mostly used to return new memory allocations.

If this is so, how does the above return actually work (the return address of a struct tm). Is the returned object defined somewhere?

Thanks

question from:https://stackoverflow.com/questions/8694365/how-is-the-result-struct-of-localtime-allocated-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The pointer returned by localtime (and some other functions) are actually pointers to statically allocated memory. So you do not need to free it, and you should not free it.

http://www.cplusplus.com/reference/clibrary/ctime/localtime/

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

EDIT : Appending a few things mentioned in the comments.

A direct result of this shared data-structure is that localtime and similar functions are not thread-safe. The thread-safe solution varies with different platforms. localtime_r for POSIX and localtime_s for MSVC.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...