0

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 printfs 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?

Mefitico
  • 816
  • 1
  • 12
  • 41
  • 2
    Note that [`localtime`](https://en.cppreference.com/w/c/chrono/localtime) can fail, and return a null pointer. Think bout what happen when you dereference a null pointer. – Some programmer dude Jun 19 '19 at 19:50
  • 1
    My understanding is that you have a problem if you call the function from different threads, so you have a race condition. Suggestions: you can use localtime_r if you are working on posix, and localtime_s if you are on windows. You can use use a #ifdef to conditionally enable them and wrap them all in a function to provide a somewhat portable alternative. Caution: the 2 functions require the same inputs but swapped. Caution 2: it looks like C11 has localtime_s (called as Windows) but with the input order to localtime_r . – CuriouslyRecurringThoughts Jun 19 '19 at 19:54
  • @CuriouslyRecurringThoughts : I need to implement a solution for both windows and linux, so thanks for indicating both `localtime_r` and `localtime_s`. Nonetheless, this seems to solve the issue with `localtime`, but alter on I still get the problem on `mktime`. – Mefitico Jun 19 '19 at 20:12
  • 1
    @Mefitico then, most likely, is as "Some programmer dude" says: localtime return a NULL, you might want to add a check to validate the idea. – CuriouslyRecurringThoughts Jun 19 '19 at 20:19
  • 1
    `localtime_s` is added in C11, so it should work on linux too, or any C11 compiler. – KamilCuk Jun 19 '19 at 22:38

0 Answers0