Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does returned struct of localtime() need to be freed?

struct tm *localtime(const time_t *timep);

I checked man localtime but there's no words on whether it's my duty to clean it after using.

And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?

like image 296
wireshark Avatar asked Jun 02 '11 05:06

wireshark


2 Answers

This information should be in the man page - my localtime man page says:

The return value points to a statically allocated struct...

Statically allocated objects should not be passed to free(), so this is your answer - no, you should not free the return value of localtime().

The only way to tell in the general case is to consult the documentation or implementation of the function in question.

like image 59
caf Avatar answered Sep 28 '22 06:09

caf


You're right to be concerned about functions that return pointers to static data - they are frequently not thread-safe, and it's good practice to avoid them, even if your code is not yet used in a multithreaded environment.

It's better to use the _r form of these functions, i.e. localtime_r()

like image 40
Roddy Avatar answered Sep 28 '22 05:09

Roddy