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

David Laight
2023-08-21T08:39:18Z

From: Alejandro Colomar <alx@kernel.org>
> 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)