RE: struct_size() using sizeof() vs offsetof()

From: David Laight
Date: Mon Aug 21 2023 - 04:39:18 EST


From: Alejandro Colomar <alx@xxxxxxxxxx>
> Sent: Thursday, August 17, 2023 7:38 PM
>
> Hi Gustavo,
>
> On 2023-08-17 18:05, Gustavo A. R. Silva wrote:
> >
> >> - tp_c = kzalloc(sizeof(*tp_c), GFP_KERNEL);
> >> + tp_c = kzalloc(struct_size(tp_c, hlist->ht, 1), GFP_KERNEL);
> >
> > I just sent a fix[1].
> >
> > Thanks for reporting this! :)

Perhaps struct_size() should include an assertion that:
(offsetof(type, field[8]) > sizeof (type))
That will ensure that field is an array member and reasonably
near the end of the structure.

A more complex calculation (using _Alignof(type) and the offset/size
of field) could be used.
But I don't think you can actually detect it is field[] (or even the
last member).

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)