leahneukirchen/nq

nq.c: fix time_t overflow on 32-bit machines

lv-zheng opened this issue · 2 comments

In systems where time_t is defined as 32-bit integer, the multiplication
by 1000 to get millisecond will cause an integer overflow.

Debug log:

(gdb) b 87
Breakpoint 1 at 0x8048b4e: file nq.c, line 87.

...

Breakpoint 1, main (argc=1, argv=0xbffff954) at nq.c:87
87      ms = started.tv_sec*1000 + started.tv_usec/1000;
(gdb) n
89      while ((opt = getopt(argc, argv, "+htw")) != -1) {
(gdb) p ms
$1 = 445515412
(gdb) p started
$2 = {tv_sec = 1439259559, tv_usec = 572464}

Fix this problem by explicit integer conversion. Patch available:

From c6f0b7e91d99bec927b89ba4127e6a1b5ffa2d07 Mon Sep 17 00:00:00 2001
From: Lv Zheng <lv.zheng.2015@gmail.com>
Date: Tue, 11 Aug 2015 02:23:03 +0000
Subject: [PATCH] nq.c: fix time_t overflow on 32-bit machines

In systems where time_t is defined as 32-bit integer, the multiplication
by 1000 to get millisecond will cause an integer overflow.

Fix this problem by explicit integer conversion.

---
 nq.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/nq.c b/nq.c
index 86177f3..7401c2e 100644
--- a/nq.c
+++ b/nq.c
@@ -84,7 +84,7 @@ main(int argc, char *argv[])

    /* timestamp is milliseconds since epoch.  */
    gettimeofday(&started, NULL);
-   ms = started.tv_sec*1000 + started.tv_usec/1000;
+   ms = (int64_t)started.tv_sec*1000 + started.tv_usec/1000;

    while ((opt = getopt(argc, argv, "+htw")) != -1) {
        switch (opt) {
-- 
2.5.0

Sigh, I thought I had checked this, but I must have done some mistake. Thanks. :)

Applied.