I have the following function that is repeatedly called within a larger program:
double troublesome_function() {
time_t time_ini = time(NULL);
struct tm tm_ini = *localtime(&time_ini);
(...)
time_t secs_passed;
secs_passed = mktime(&tm_ini);
double return_value =0;
return_value = (double)secs_passed;
return(return_value);
}
Most of the time, it works just fine. But in a few cases the line *localtime(&time_ini)
causes a Segmentation Fault. Removing this initialization from tm_ini
seems okay, but then the code will again run fine in most cases but the line mktime(&tm_ini)
will cause a segmentation fault. Finally, the return operation may also be at error, which I've checked by adding printf
s to the code.
According to this answer "One gotcha with localtime
is the returned pointer is a pointer to a static global var and subsequent calls to localtime
update the var."
I'm suspicious that the repeated calls to mktime
are causing this behavior, so by adding a static counter variable, this happens at the 94th call.
Any way to prevent functions from time.h
from suffering this interference?