A
arnuld
WANTED: How to handle integer overflows (and overflows in general)
#include <stdio.h>
#include <limits.h>
#include <errno.h>
int main(void)
{
int i, j, k;
errno = 0;
j = k = INT_MAX;
i = j + k;
printf("i = %d, errno = %d, ERANGE = %d\n", i, errno, ERANGE);
return 0;
}
===================== OUTPUT ============================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra test.c
[arnuld@dune programs]$ ./a.out
i = -2, errno = 0, ERANGE = 34
[arnuld@dune programs]$
It overflows of course, (OT) gcc does not give any error even when all
flags are on (/OT). errno does not work, its value is still zero after
that overflow. In this case how to check for overflow ? I have checked
FAQs and 20.6b gives a technique to handle this which I have applied down
here, it works fine but I am not sure it will still work if I change line
j = k = INT_MAX to j = k = INT_MIN
int main(void)
{
int i, j, k;
errno = 0;
j = k = INT_MAX;
if(INT_MAX - j < k)
{
printf("Overflow error\n");
i = INT_MAX;
}
else
{
i = j + k;
}
printf("i = %d, errno = %d, ERANGE = %d\n", i, errno, ERANGE);
return 0;
}
NOTE: Came to think of this exercise because of this article that claims
"Nearly all binary searches and mergesorts are broken". Author talsk
about line 6 but I think line 3 will overflow issue if written in C, if
a.length comes out to be greater than INT_MAX.
http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-
nearly.html
#include <stdio.h>
#include <limits.h>
#include <errno.h>
int main(void)
{
int i, j, k;
errno = 0;
j = k = INT_MAX;
i = j + k;
printf("i = %d, errno = %d, ERANGE = %d\n", i, errno, ERANGE);
return 0;
}
===================== OUTPUT ============================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra test.c
[arnuld@dune programs]$ ./a.out
i = -2, errno = 0, ERANGE = 34
[arnuld@dune programs]$
It overflows of course, (OT) gcc does not give any error even when all
flags are on (/OT). errno does not work, its value is still zero after
that overflow. In this case how to check for overflow ? I have checked
FAQs and 20.6b gives a technique to handle this which I have applied down
here, it works fine but I am not sure it will still work if I change line
j = k = INT_MAX to j = k = INT_MIN
int main(void)
{
int i, j, k;
errno = 0;
j = k = INT_MAX;
if(INT_MAX - j < k)
{
printf("Overflow error\n");
i = INT_MAX;
}
else
{
i = j + k;
}
printf("i = %d, errno = %d, ERANGE = %d\n", i, errno, ERANGE);
return 0;
}
NOTE: Came to think of this exercise because of this article that claims
"Nearly all binary searches and mergesorts are broken". Author talsk
about line 6 but I think line 3 will overflow issue if written in C, if
a.length comes out to be greater than INT_MAX.
http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-
nearly.html