Auto variable with sizeof == 0

colin at vu-vlsi.UUCP colin at vu-vlsi.UUCP
Sat Feb 14 02:24:07 AEST 1987


In article <159 at batcomputer.tn.cornell.edu> braner at batcomputer.UUCP (braner) writes:
>
>In the famous "microEMACS" by David Conroy, which has been widely
>utilized and modified, the basic text-line structure looks like this:
>
>typedef struct LINE {
>	struct LINE *nextline;
>	struct LINE *prevline;
>	short       size;		/* s.b. int! */
>	short       used;
>	char        text[];		/* !!!!!!!!! */
>}	LINE;
>
>The idea is to allocate memory for lines as follows:
>
>	lineptr = malloc(sizeof(LINE)+length);

Some other people suggested declaring the text field to be char *text, but
I'm surprised no one suggested this:

Declare the text field to be char text[1], then use

	lineptr = malloc(sizeof(LINE)-1+length);

Almost all compilers will optimize sizeof(LINE)-1 into a single constant, so
the code generated is likely to be exactly the same as that generated for
the uEmacs example above...[Of course you can cast the argument to (unsigned)
to keep lint happy.]

Gnuplot (which we posted a couple weeks ago) uses this technique because it
seemed to be the most portable...

	-Colin Kelley  ..{cbmvax,pyrnj,bpa}!vu-vlsi!colin



More information about the Comp.lang.c mailing list