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

Alejandro Colomar
2020-08-25T11:49:17Z

Hi Michael,

On 8/25/20 1:41 PM, Michael Kerrisk (man-pages) wrote:

>> In C, successive multiplications are evaluated left to right (*), and
>> therefore here is what happens:
>>
>> ``(sizeof(x) * INT_MAX * 2)``:
>>
>> 1) sizeof(x) * INT_MAX (the type is the largest of both, which is
>> size_t (unsigned long; uint64_t)).
>> 2) ANS * 2 (the type is again the largest: size_t)
>>
>> ``(INT_MAX * 2 * sizeof(x))``:
>>
>> 1) INT_MAX * 2 (the type is the largest of both, which is
>> int as both are int (int; int32_t), so the
>> result is already truncated as it doesn't fit
>> an int; at this point, the intermediate result
>> will be 2^32 - 2 (``INT_MAX - 1``) (if I did
>> the math right)).
>> 2) ANS * 2 (the type is again the largest of both: size_t;
>> however, ANS was already incorrect, so the
>> result will be an incorrect size_t value)
>>
>>> sizeof((sizeof(x) * INT_MAX * 2)) == 8
>>
>> Here you were overflowing a uint64_t (if x were a char, it would not
>> overflow, and the result would be close to UINT64_MAX).

I also goofed :) I didn't see the sizeof applying to everything.
And I was wrong: you aren't overflowing 64 bits, which would need x to
be enormous. But the idea is there; the explanation above was right.

>>
>>> sizeof(INT_MAX * 2 * sizeof(x)) == 8
>>
>> Here you were overflowing int32_t, and it would overflow regardless of
>> sizeof(x).
>
> Thanks for the lesson in C basics. I clearly did need a refresher :-}.

You're welcome! It happens me from time to time too. :)

>
> You and Jakub are of course correct.
>
> If you send the patches in the order (as I numbered in my previous reply):
>
> (1)
> (3)
> (2) as multiple pieces
>
> that would be best, since the first two patches should obviously be
> applied, and then we can discuss the last patch(es) case by case.

Ok.

>
> Thanks,
>
> Michael
>

Cheers,
Alex.