Ælex
Ælex

Reputation: 14839

C++ linux time freezes application

I am importing <sys/time.h> and using the

struct time_t *start;

A class has a member time_t *start; and a member function getETA() :

template <class S, class P> 
double Task<S,P>::getETA()
{ 
  time_t *stop;
  time(stop);
  return difftime(*stop , *start);
}

Also note that time_t *start is initialized in the class constructor.

Whenever I call getETA() the application freezes. Even more interesting, I used the same structures and code in the main.cpp in the main loop, and apparently it also freezes the application:

int main(int argc, char **argv) 
{ 
  ...
  time_t *start;
  time(start);
  ...
}

Am I using it the wrong way ? I remember in some application a long time ago, that is how I used it and it worked fine.

Upvotes: 2

Views: 446

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361522

You've to pass a valid pointer to time() function. So why don't you do this:

time_t start;
time(&start);

time_t stop;
time(&stop);

That is, don't declare start and stop as pointer. Declare them as non-pointer, automatic variables.

If you declare them as pointers, then you've to do this:

time_t *start = new time_t;
time(start);

time_t *stop  = new time_t;
time(stop);

//...

//Must deallocate the memory when you don't need them anymore
delete start;
delete stop; 

But I wouldn't suggest this. I would suggest you to go with non-pointer variables.

Upvotes: 7

John Carter
John Carter

Reputation: 55291

Change it to:

int main(int argc, char **argv) 
{ 
  ...
  time_t start;
  time(&start);
  ...
}

The problem is that the function was expecting a pointer to a valid time_t, but you passed it a time_t pointer that is uninitialised, which results in undefined behaviour.

Upvotes: 5

Related Questions