Re: [patch] memusage.1, bind.2, eventfd.2, futex.2, open_by_handle_at.2, perf_event_open.2, poll.2, signalfd.2, sysctl.2, timerfd_create.2, bsearch.3, cmsg.3, getaddrinfo.3, getaddrinfo_a.3 getgrouplist.3, insque.3, malloc_info.3, mbsinit.3, mbstowcs.3, pthread_create.3, pthread_setaffinity_np.3, queue.3, rtnetlink.3, shm_open.3, strptime.3, tsearch.3, aio.7, fanotify.7, inotify.7, unix.7: Use sizeof consistently

Michael Kerrisk (man-pages)
2020-08-25T11:36:30Z

Hi Jakub,

Once again, thanks for jumping in...

On Tue, 25 Aug 2020 at 13:19, Jakub Wilk <jwilk@jwilk.net> wrote:
>
> * Michael Kerrisk <mtk.manpages@gmail.com>, 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...

Yes, I goofed :-(. There is no compiler warning for "sizeof(INT_MAX *
2 * sizeof(x))", which is what I tested, but as you point out, there
is a warning for "INT_MAX * 2 * sizeof(x)".

Thanks,

Michael

--
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/