0

I have an application that calls gettimeofday to store the tv_sec in which that part of the code starts to run. This code is very simple:

struct timeval tvnow;
gettimeofday(&tvnow);
int initialTime = tvnow.tv_sec;

It normally works fine but sometimes I am getting unexpected results such as

tvnow = {tv_sec = 1024, tv_usec = 0}
initialTime = 1401591

Or

tvnow = {tv_sec = 1024, tv_usec = 0}
initialTime = 2439903

Why could this happen?

Regards

althor
  • 739
  • 2
  • 9
  • 21

1 Answers1

1

You are calling gettimeofday() with the wrong number of arguments. The resulting behavior is undefined. If you don't want the timezone information, then pass NULL as the second argument:

struct timeval tvnow;
gettimeofday(&tvnow, NULL);
int initialTime = tvnow.tv_sec;

I'm going to suppose that somehow you're including a combination of headers that include a definition of struct timeval (or else you're providing your own definition), but not a prototype for gettimeofday(). If there were a correct prototype visible at the point of the function call, then the code oughtn't to compile at all. If your compiler doesn't issue a warning about the absence of a prototype then you ought to either figure out how to make it do so (and compile always that way), or get a better compiler.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157