I have created a function to calculate the difference of 2 timeval functions. Here is the basic version of that function.
struct timeval* getDifference(struct timeval* startTime, struct timeval* finishTime)
{
struct timeval* difference = new struct timeval;
difference->tv_sec = finishTime->tv_sec - startTime->tv_sec;
difference->tv_usec = finishTime->tv_usec - startTime->tv_usec;
return difference;
}
int main()
{
struct timeval a,b;
struct timeval* c;
gettimeofday(&a, NULL);
usleep(100000);
gettimeofday(&b, NULL);
c = getDifference(&a, &b);
}
What i want to know is if the usage struct timeval* c; safe? or should it be like struct timeval* c = new struct timeval;?
If it is safe then would freeing c free the difference = new struct timeval; allocated inside the function?
I would suggest not using pointers at all in your case. Let the arguments be references have the return be copied: