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

Marc W. Mengel mmengel at cuuxb.ATT.COM
Thu Dec 21 04:28:02 AEST 1989


In article <468 at bbxsda.UUCP> scott at bbxsda.UUCP (Scott Amspoker) writes:
>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? */

Gee guys, you *told* the compiler that foo->baz only has one
character in it; of *course* it's wrong to reference 
foo->baz[1].  Yes, you can probably make strcpy scribble
where foo->baz[1] would have been if baz had been declared
baz[2] on most machines, but why live dangerously? Sooner
or later you will find a machine with really wierd base/offset
limitations, and a compiler will try to generate

	mov.b $1,8(%a2)

when the offset "n" on a "n(%am)" can only be 0..7, and you'll
be sorry.  The compiler will have been correct in it's code
generation because it "knew" that the subscript had to be
zero.
-- 
 Marc Mengel					mmengel at cuuxb.att.com
 						attmail!mmengel
 						...!{lll-crg|att}!cuuxb!mmengel



More information about the Comp.std.c mailing list