[PATCH 2/2] os: Work around integer overflow in TimerSet.

Cyril Brulebois kibi at debian.org
Sun Mar 6 12:57:05 PST 2011


Hi,

Fernando Carrijo <fcarrijo at freedesktop.org> (06/03/2011):
> I found this, buried in Section 6.2.5 (9) of the C Standard:
> 
>     A computation involving unsigned operands can never overflow,
>     because a result that cannot be represented by the resulting
>     unsigned integer type is reduced modulo the number that is one
>     greater than the largest value that can be represented by the
>     resulting type.
> 
> So, I presume, something isn't quite right in this series.

I suggest you try that yourself:
,---
  #include <stdio.h>
  #include <X11/Xmd.h>

  int main(void) {
    CARD32 a = (CARD32)(~0)/5*4;
    CARD32 b = (CARD32)(~0)/5*2;
    CARD32 c = (CARD32)(~0)/5*1;
    CARD32 s;
    printf("max : %u\n", (CARD32)(~0));
    printf("a   : %u\n", a);
    printf("b   : %u\n", b);
    printf("c   : %u\n", c);
    s=(a+b>a) ? (a+b) : ((CARD32)(~0));
    printf("sum1: %u\n", s);
    printf("sum2: %u\n", (a+b));
    a+=b;
    printf("+=  : %u\n", a);
    return 0;
  }
`---

Getting this:
,---
  $ gcc bar.c && ./a.out
  max : 4294967295
  a   : 3435973836
  b   : 1717986918
  c   : 858993459
  sum1: 4294967295
  sum2: 858993458
  +=  : 858993458
`---

See? It overflows, with a+b == c, as seen in sum2 or +=. And the
“expected” result in sum1.

KiBi.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: Digital signature
URL: <http://lists.x.org/archives/xorg-devel/attachments/20110306/3cf604bd/attachment.pgp>


More information about the xorg-devel mailing list