# (C in bsd) time functions like ctime and localtime not working



## neel1982 (Sep 4, 2005)

following are the code snippets. I have added time.h
i am working on freebsd platform

1.>>> time_t tim=time(NULL);
tm *now = localtime(&tim); //this is where segementation fault happens
cout<<now<<"\n";

2.>>>
time_t tim=time(NULL);
char *s=ctime(&tim); //this is where segmentation fault happens
s[strlen(s)-1]=0; 
printf("it is %s now.\n", s);

Please help


----------



## aewarnick (Sep 3, 2002)

FreeBSD, Great!

Try this:
time_t tim; time(tim);
tm *now= localtime(&tim);
cout<<now<<"\n";


----------



## AGCurry (Jun 15, 2005)

It looks okay to me, except in your first example, it should be "struct tm *now" - I assume that your code includes the word struct, or the program wouldn't compile.

Are you sure cout is overloaded for struct tm* ?

aewarnick, the time() function requires a pointer as its argument. To do what you're suggesting, tim would have to be time_t *, and it would be localtime( tim ).

The second example has me stumped; it sure looks like it should work. Perhaps it's dumping when you try to manipulate the memory that ctime() has returned a pointer to? Try declaring a char array and copying ctime() to it. That would eliminate that concern.


----------



## aewarnick (Sep 3, 2002)

My mistake corrected:
time_t tim; time(&tim);

I haven't tested any of the code but it's worth a try.


----------

