* Michael Kerrisk <mtk.manpages@xxxxxxxxx>, 2020-08-25, 12:29:
``(sizeof(x) * INT_MAX * 2)`` doesn't overflow.
``(INT_MAX * 2 * sizeof(x))`` overflows, giving incorrect
results.
(3) Is this true? "gcc -Wall" does not complain about this.
My GCC (10.2.0) does, even without -Wall:
$ gcc test-overflow.c
test-overflow.c: In function 'main':
test-overflow.c:8:52: warning: integer overflow in expression of type 'int' results in '-2' [-Woverflow]
8 | printf("INT_MAX * 2 * sizeof(x) = %zu\n", INT_MAX * 2 * sizeof(x));
| ^
sizeof((sizeof(x) * INT_MAX * 2)) == 8
sizeof(INT_MAX * 2 * sizeof(x)) == 8
Hmm? If there was no overflow, surely you should get a number larger
than INT_MAX...
--
Jakub Wilk
#include <stdio.h>
#include <limits.h>
int main(int arg, char **argv)
{
typedef int x;
printf("sizeof(x) * INT_MAX * 2 = %zu\n", sizeof(x) * INT_MAX * 2);
printf("INT_MAX * 2 * sizeof(x) = %zu\n", INT_MAX * 2 * sizeof(x));
}