> On Sep 10, 2024, at 14:48, Martin Uecker <uec...@tugraz.at> wrote:
> 
> Am Dienstag, dem 10.09.2024 um 20:36 +0200 schrieb Jakub Jelinek:
>> 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
> 
> (offset + sizeof * c) could be smaller than sizeof (*(*__p))).

Yes, that’s the reason.

[ ~]$ cat t.c
#include <stdio.h>
#include <stddef.h>
struct flex {
 int b;
 char other;
 char c[];
} *array_annotated;

int main ()
{
 printf ("the size of struct is %d \n", sizeof(struct flex));
 printf ("the offset of c is %d \n", offsetof(struct flex, c));
 return 0;
}

[ ~]$ gcc t.c; ./a.out
the size of struct is 8 
the offset of c is 5 

Then if we only allocate 2 elements for the FAM “c”,  then offset  + sizeof 
(char) * 2 = 5 + 2 = 7, which is smaller than sizeof (struct flex), 8.

Qing

> 
> Martin
> 
> 
>> 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