Reputation: 1
I have been working with C and I thought that a pointer should not point to a local variable, but the library holds a function gmtime(), which seems to return a pointer to a variable created inside of it. Is my understanding correct?
time_t epochTime;
time(&epochTime);
struct tm *currentTime=gmtime(&epochTime);
Upvotes: 0
Views: 182
Reputation: 2610
It's not returning a pointer to a local variable, rather it is returning a pointer to a statically allocated memory region.
From man page:
The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.
A statically allocated memory region could simply be a global variable, or a static
local variable. The latter does not exist on the stack, but rather in the data
segment along with other statically-allocated data member.
Upvotes: 0
Reputation: 224387
Internally, gmtime
contains a variable declared with the static
storage class specifier. That means that the variable has full program lifetime and therefore it is valid to return its address from the function.
This also means that if you save that pointer somewhere and call gmtime
again with a different parameter, it changes what the saved pointer points to.
Upvotes: 1