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

Karl Heuer karl at haddock.ima.isc.com
Fri Dec 22 09:00:00 AEST 1989


Here's a challenge to those who believe that expandable structs are not legal
in a strictly conforming program.  I have enclosed six code fragments.  If you
agree that [0] is clearly legal (it doesn't even use the struct-pointer
|foo|), but maintain that [5] is not, then there must be some value n for
which you believe that fragment [n-1] is legal but fragment [n] is not.  I
would be interested in hearing where you would draw the line, and your reasons
for believing that the legality changes at that point.

Assume global declarations
	typedef struct foo_struct { int bar; char baz[1]; } T;
	T *foo;  void *vp;  char *cp;

[0]	vp = malloc(sizeof(T)+1);
	foo = (T *)vp;
	cp = (char *)vp;
	cp[offsetof(T, baz[0]) + 1] = '\0';

[1]	foo = (T *)malloc(sizeof(T)+1);
	cp = (char *)foo;
	cp[offsetof(T, baz[0]) + 1] = '\0';

[2]	foo = (T *)malloc(sizeof(T)+1);
	cp = (char *)foo + offsetof(T, baz[0]) + 1;
	*cp = '\0';

[3]	foo = (T *)malloc(sizeof(T)+1);
	cp = (char *)(&foo->baz[0]) + 1;
	*cp = '\0';

[4]	foo = (T *)malloc(sizeof(T)+1);
	cp = &foo->baz[1];
	*cp = '\0';

[5]	foo = (T *)malloc(sizeof(T)+1);
	foo->baz[1] = '\0';

(Please don't bother to reply if you haven't read at least one draft of the
Standard.  The question is not whether it's useful, nor whether current
compilers do or do not accept it, but whether the pANS permits it.)

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.std.c mailing list