I have this code:
int tim=10000; // some random number
tm *now=localtime(&tim);
printf("Date is %d/%02d/%02d\n", now->tm_year+1900, now->tm_mon+1, now->tm_mday);
printf("Time is %02d:%02d\n", now->tm_hour, now->tm_min);
The reason that I am wondering if it has memory leak is that localtime returns a pointer to a struct which means that it allocate memory. but nobody release it.
Is there any memory leak on this code?
The primary tools for detecting memory leaks are the C/C++ debugger and the C Run-time Library (CRT) debug heap functions. The #define statement maps a base version of the CRT heap functions to the corresponding debug version. If you leave out the #define statement, the memory leak dump will be less detailed.
In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.
You don't (and shall not) have to explicitly free anything as localtime
returns a pointer to a static object.
C Standard says:
(C11, 7.27.3 Time conversion functions p1) "Except for the strftime function, these functions each return a pointer to one of two types of static objects: a broken-down time structure or an array of char."
And from POSIX.1-2008 documentation,
The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With