Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!tut.cis.ohio-state.edu!mailrus!ncar!unmvax!bbx!bbxsda!scott From: scott@bbxsda.UUCP (Scott Amspoker) Newsgroups: comp.std.c Subject: Re: "expandable" structs with last element declared using [1] Message-ID: <468@bbxsda.UUCP> Date: 18 Dec 89 16:32:18 GMT References: <463@cpsolv.UUCP> <477@longway.TIC.COM> Reply-To: scott@bbxsda.UUCP (Scott Amspoker) Organization: Basis International, Albuquerque, NM Lines: 38 In article <477@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