On Tue, Sep 10, 2024 at 06:31:23PM +0000, Qing Zhao wrote:
> 
> 
> > On Sep 10, 2024, at 14:09, Jakub Jelinek <ja...@redhat.com> wrote:
> > 
> > On Tue, Sep 10, 2024 at 06:02:45PM +0000, Qing Zhao wrote:
> >>> #define alloc(P, FAM, COUNT) ({ \
> >>> __auto_type __p = &(P); \
> >>> __auto_type __c = (COUNT); \
> >>> size_t __size = sizeof(*(*__p)) + sizeof(*(*__p)->FAM) * __c; \
> > 
> > Shouldn't that be
> >  size_t __size = offsetof(__typeof(*__p), FAM) + sizeof(*(*__p)->FAM) * 
> > __c; \
> > ?
> 
> Yeah, I think that the correct size computation should be:
> 
> #define MAX(A, B) (A > B) ? (A) : (B)
> size_t __size = MAX (sizeof (*(*__p)), offsetof(__typeof(*__p), FAM) + 
> sizeof(*(*__p)->FAM) * __c); \

No, why?  sizeof (*(*__p)) should be always >= offsetof(__typeof(*__p), FAM),
you can't have an offset outside of a structure (ok, except doing something
like use fld[100] as FAM).  offsetof + sizeof (elt) * count is the actually
needed size, say if it is
struct S { size_t a; char b; __attribute__((counted_by (a))) char c[]; };
then you don't really need 2 * sizeof (size_t) + N size of N elements
in the flexible array, just sizeof (size_t) + 1 + N is enough.

Or is counted_by attribute handling it in some weird way?

        Jakub

Reply via email to