[net.lang.c] Variable-length string at end of structure

kendall@wjh12.UUCP (Sam Kendall) (06/19/84)

I am wondering how many programs use the following construct, or
something similar:

	struct a {
		...
		char varlen_string[1];
	} a_struct;
	...
	p = (struct a *) malloc(sizeof (struct a) + strlen(a_string));
	... /* fill in structure members */
	(void) strcpy(p->varlen_string, a_string);

That is, malloc'ing space for a fixed-length structure plus a
variable-length string, and referencing the string using the last member
of the structure.

The Rand Editor and its derivatives do this, and Martin Minow's cpp does
it; has anyone seen other programs that do?  I'd be interested to know
how many programs do this, and exactly what type the last member of the
structure is (i.e.  is it char [1]?  char?  Something else?) I need to
know in order to put some kludge in our runtime checker to handle it;
currently it is flagged as an error.

	Sam Kendall	{allegra,ihnp4,ima,amd70}!wjh12!kendall
	Delft Consulting Corp.	    decvax!genrad!wjh12!kendall

jdb@mordor.UUCP (John Bruner) (06/23/84)

I've used this trick in a number of programs, usually for symbol
tables and the like.  The last element of my structures is
always a one-element character array.

Several years ago, when I was first maintaining APL\11 at Purdue/EE,
I had to transport it from V6 PDP-11's running the photo7 C
compiler to a VAX running 32/V.  The program had compiled without
a hitch on Ritchie's compiler, but the pcc-derived VAX compiler
produced roughly 800 error messages.  One of them related to the
"item" structure that APL was using.  The structure was defined as:

	struct item
	{
		char	rank;
		char	type;
		int	size;
		int	index;
		data	*datap;
		int	dim[0];
	};

(This structure appears at the beginning of each data item.  Space is
allocated for the structure, "rank" elements of the array "dim", and
"size" double-precision floating-point numbers which specify the data.)

Ritchie's compiler accepted this (and perhaps still does today), but
"pcc" complained about the zero-element array "dim".  I had to recode
it so that "dim" was declared with a non-zero number of dimensions
and then fudge the allocation so that the same amount of space was
allocated.
--
  John Bruner (S-1 Project, Lawrence Livermore National Laboratory)
  MILNET: jdb@mordor.ARPA [jdb@s1-c]	(415) 422-0758
  UUCP: ...!ucbvax!dual!mordor!jdb 	...!decvax!decwrl!mordor!jdb
-- 
  John Bruner (S-1 Project, Lawrence Livermore National Laboratory)
  MILNET: jdb@mordor.ARPA [jdb@s1-c]	(415) 422-0758
  UUCP: ...!ucbvax!dual!mordor!jdb 	...!decvax!decwrl!mordor!jdb