foo.text[0] Was: Auto variable with sizeof == 0

mwm at eris.UUCP mwm at eris.UUCP
Fri Feb 20 09:08:57 AEST 1987


On the subject of dealing with structure with variable sized text
arrays, <4157 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:

>The problem is that the struct will be padded out after the one-byte
>'text' array to meet alignment requirements for the pointer fields.
>'sizeof(LINE)' includes this padding. This can be fixed by placing a
>substruct around everything but the 'text[1]' declaration, and taking
>the size of that struct instead of sizeof(LINE)-1. Or, declare a dummy
>struct with the same declarations just to get its size (and *comment
>heavily* or someone will change one and not the other). The use of a
>dummy struct instead of a substruct would allow you to leave the struct
>references unchanged. Both of these methods may fail if 'text' is
>an array of things other than chars - i.e. if padding is required
>to align 'text' on a more strict boundary than that required by any
>previous field in the struct. Nobody said it was easy :-).

I like this. Especially if you get the C preprocessor to help you like so:

#define	FUNKY_HEADER	struct LINE	*nextline;\
			struct LINE	*prevline;\
			short		size;\
			short		used;	/* Note semicolon! */

struct funky_dummmy_for_size {
	FUNKY_HEADER
	} ;

struct real_thing {
	FUNKY_HEADER
	char text[1];
	} ;

#define	get_new_real_thing(len) \
	((struct real_thing *) malloc(sizeof(funky_dummy_for_size) + len)) ;

This takes care of the problem of keeping the two versions in synch.
I'm going to look at it for the next version of mg. Of course, someone
will probably point at a good reason why this is broken before then,
anyway. :-)

	<mike





But I'll survive, no you won't catch me,		Mike Meyer
I'll resist the urge that is tempting me,		ucbvax!mwm
I'll avert my eyes, keep you off my knee,		mwm at berkeley.edu
But it feels so good when you talk to me.		mwm at ucbjade.BITNET



More information about the Comp.lang.c mailing list