Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any memory leakeage in this code?

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?

like image 514
mans Avatar asked Aug 27 '14 13:08

mans


People also ask

How do I know if my code has a memory leak?

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.

What is a memory leak in code?

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.


1 Answers

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.

like image 152
ouah Avatar answered Oct 17 '22 11:10

ouah