difftime overflows when it shouldn't

Paul Eggert eggert at twinsun.com
Tue May 3 04:36:04 UTC 1994


Let's take the common case where time_t ranges from -2147483648
through 2147483647, and `double' is IEEE 754 double precision.
Then, under tz-1994e, the program

    #include <time.h>
    #include <stdio.h>
    #define MAX_TIME 2147483647
    #define MIN_TIME (-1 - MAX_TIME)
    int main() {
      printf("difftime(%ld, %ld) = %.17g\n",
	     (long) MAX_TIME, (long) MIN_TIME, difftime(MAX_TIME, MIN_TIME));
      return 0;
    }

outputs

    difftime(2147483647, -2147483648) = -1

There's no reason for difftime to report the wrong answer, since the
result is exactly representable.  Here is a patch.

===================================================================
RCS file: difftime.c,v
retrieving revision 1994.5
retrieving revision 1994.5.1.1
diff -c -r1994.5 -r1994.5.1.1
*** difftime.c	1992/04/23 17:34:30	1994.5
--- difftime.c	1994/05/03 04:30:43	1994.5.1.1
***************
*** 13,17 ****
  const time_t	time1;
  const time_t	time0;
  {
! 	return time1 - time0;
  }
--- 13,28 ----
  const time_t	time1;
  const time_t	time0;
  {
! 	if (sizeof(time_t) < sizeof(double))
! 		return (double) time1 - (double) time0;
! 	else {
! 		time_t delta = time1 - time0;
! 		if ((~time1 & time0 & delta) < 0) {
! 			time_t hibit;
! 			for (hibit = 1;  (hibit <<= 1) > 0;  )
! 				;
! 			return delta - 2.0 * hibit;
! 		} else
! 			return delta;
! 	}
  }



More information about the tz mailing list