2

I was using localtime on my BeagleBone Black to time stamp events. I'm running a multi-threaded application and realized that localtime is not thread safe. So I switched to localtime_r and this generates a segmentation fault. Please find attached the image.

enter image description here

  • I executed the same program on my Desktop which is x86_64 system with a different linux kernel version and it works. Tried it again with another 64 bit system with a more recent kernel and it does not work.
  • Did not find much literature online regarding this issue. This has some info but is not clear.

Any suggestions on how I can solve this? Not sure why it works on some systems and not on others.

Update 1: I've posted the code

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>


int main(){

int day, month, hour, minute, second, year;

time_t t = time(NULL);
struct tm *result;
struct tm *tm = localtime_r(&t, result);

day = result->tm_mday;
month = (result->tm_mon+1);
hour = result->tm_hour;
minute = result->tm_min;
second = result->tm_sec;
year = (result->tm_year-100);


printf("%d : %d : %d : %d:%d:%d\n", month, day, year, hour, minute, second);

return 0;
}
am3
  • 681
  • 2
  • 12
  • 30

2 Answers2

4
struct tm *result;
struct tm *tm = localtime_r(&t, result);

You passed garbage to localtime_r. You didn't initialize result to anything in particular but passed its value to localtime_r.

Perhaps you wanted:

time_t t = time(NULL);
struct tm result;
struct tm *tm = localtime_r(&t, &result);
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
3

Seg fault is occurring as you are trying to access a memory which you do not own.
Use this

//struct tm *result ;
struct tm result;
struct tm *tm = localtime_r(&t, &result);
µtex
  • 900
  • 5
  • 12