Size of structure containing char fields

Scott David Daniels daniels at ogicse.ogc.edu
Sat Jul 28 06:53:42 AEST 1990


In article <8631 at cognos.UUCP> jimp at cognos.UUCP (Jim Patterson) writes:
>In article <1030 at lzaz.ATT.COM> bds at 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 <stddef.h>
>   #include <stdlib.h>
>   ...
>   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 at cse.ogi.edu



More information about the Comp.std.c mailing list