Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uwm.edu!ogicse!daniels From: daniels@ogicse.ogc.edu (Scott David Daniels) Newsgroups: comp.std.c Subject: Re: Size of structure containing char fields Summary: don't use offsetof to calculate sizes Message-ID: <10886@ogicse.ogc.edu> Date: 27 Jul 90 20:53:42 GMT References: <1030@lzaz.ATT.COM> <8631@cognos.UUCP> Followup-To: comp.std.c Organization: Oregon Graduate Institute (formerly OGC), Beaverton, OR Lines: 41 In article <8631@cognos.UUCP> jimp@cognos.UUCP (Jim Patterson) writes: >In article <1030@lzaz.ATT.COM> bds@lzaz.ATT.COM (Bruce Szablak) writes: >>Is there a portability problem with the following structure where the >>array is intended to support a variable length array? >> >> struct example2 { char a, b, c[1]; }; > >I think this approach is reasonably portable if you use offsetof >instead of relying on the sizeof() operator. E.g. to allocate the >structure allowing the array "c" to be "n" bytes long: > > #include > #include > ... > struct example2 { char a, b, c[1]; }; > struct example2 *ptr = malloc(offsetof(struct example2, c) + n); >-- >Jim Patterson Cognos Incorporated >UUCP:decvax!utzoo!dciem!nrcaer!cognos!jimp P.O. BOX 9707 >PHONE:(613)738-1440 3755 Riverside Drive > Ottawa, Ont K1G 3Z4 I think you had better not follow the offsetof advice, it provides the offset of the field in the record, and should not be thought of as providing the length of the record up to that point. It is a tiny point, but note that structure assignment (if used) may copy the entire sizeof(struct) block, while struct example2 *ptr = malloc(offsetof(struct example2, c) + n); may allocate a small block (less than sizeof(structexample2)) if, for example, n is 0. Code like: struct example2 *ptr = malloc(sizeof(struct example2) + strlen(name) ); (void) strcpy( ptr->c, name ); may over-allocate (if the system is padding the record), but it will always provide enough room, and never under-allocate. -Scott Daniels daniels@cse.ogi.edu