You are not logged in.
I'm working on a project and need to print a timestamp, and have the following code:
#include <stdio.h>
#include <sys/time.h>
int main()
{
struct timeval ts;
time_t mytime;
mytime = (time_t)ts.tv_sec;
printf("%s\n",ctime(&mytime));
return 0;
}
This compiles fine, but results in a segmentation fault on my machine. I'm running in on a 64 bit arch desktop. However, the same code runs perfectly well on a 32 bit minix virtual machine.
Any explanations, or is this a bug?
Last edited by kwhershey (2012-12-06 03:36:11)
Offline
Sorry, I retype my code and missed a line. I do gettimeofday before I set mytime and it still fails.
Offline
I'm not at my computer right now, but what header is required? I'd look at the man page otherwise.
But if I'm missing the header that includes ctime, why am I able to compile? Shouldn't it spit an error while compiling? Or does the compiler assume it will get a definition at some point then never does?
In minix, ctime is defined in sys/time.h, so I assumed it crossed over.
Offline
I'm not at my computer right now, but what header is required? I'd look at the man page otherwise.
time.h defines ctime. sys/time.h defines some additional types.
But if I'm missing the header that includes ctime, why am I able to compile? Shouldn't it spit an error while compiling? Or does the compiler assume it will get a definition at some point then never does?
If you enable warnings, you'll get an implicit definition warning for ctime. In this case, the compiler assumes that it takes a single arg and returns an int. When it gets to the linker phase, it happens to finds a symbol in libc that matches the name (symbols know nothing of their arguments and return type) and presents you with a linked binary.
In minix, ctime is defined in sys/time.h, so I assumed it crossed over.
If minix defines ctime in sys/time.h, it deviates from POSIX and the ISO C standard.
Offline