Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 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

See Question&Answers more detail:os

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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...