"expandable" structs with last element declared using [1]

Scott Amspoker scott at bbxsda.UUCP
Tue Dec 19 03:32:18 AEST 1989


In article <477 at longway.TIC.COM> uunet!sq!msb (Mark Brader) writes:
>The issue is the legality of:
>
>    struct foo_struct {
>	int bar;
>	char baz[1];
>    } *foo;
>
>    foo = (struct foo_struct *) malloc(sizeof(struct foo_struct)+1);
>    foo->baz[1] = 1;  /* error? */
>
>[Note that it is not disputed that, if this IS done, an assignment of
>*foo to another struct foo_struct won't copy the entire contents of the
>"extended" baz member; for this reason if no other, the construct may
>be undesirable.]
>
>Both Doug Gwyn and Dennis Ritchie have recently stated without proof,
>unless I misunderstood them, that this is not safe.  I believe Doug has
>stated that there are implementations where it doesn't work, but hasn't
>named any.  Can someone do so (in comp.lang.c)?

Don't expect anyone on comp.lang.c to provide proofs (which is why
I unsubscribed to that group some time ago).  If they had their way
"a=b" would not be portable.  If worst comes to worst, your example may
end up allocating a little more memory than necessary but I see no way you
would get screwed unless sizeof(char) is more than 1.  Perhaps you should say:
 
       malloc(sizeof(struct foo_struct)+sizeof(char))

Maybe someone thinks that structure fields need not be allocated in
any particular order.  I wouldn't be surprised if it didn't work on
some system somewhere, but such a system is probably at fault.

-- 
Scott Amspoker
Basis International, Albuquerque, NM
(505) 345-5232
unmvax.cs.unm.edu!bbx!bbxsda!scott



More information about the Comp.std.c mailing list