Auto variable with sizeof == 0

dhb at rayssd.UUCP dhb at rayssd.UUCP
Fri Feb 13 04:06:57 AEST 1987


In article <159 at batcomputer.tn.cornell.edu> braner at batcomputer.UUCP (braner) writes:
> [much discussion of a structure with a trailing character string
> and the fact that the way it is being used is illegal.  also
> mention of the fact that the overhead of an extra pointer and
> malloc control block might be critical factors.]

I have run into this problem on several occasions and have come up with
what I think is a reasonable solution (actually two solutions).  The
approach that I prefer is the following:

	1. change the definition of 'text' to 'char *text;'
	2. do the malloc() for 'sizeof(LINE)+length'
	3. set the text pointer to the base address of the structure
	   plus sizeof(LINE).

This approach has the added overhead of an extra pointer but it
eliminates the extra malloc control block.  Since the malloc control
block is generally larger than a pointer this is a reasonable tradeoff.
It also eliminates the extra call to malloc which can be important if
you want your application to run fast.

Another approach that I have used is to define multiple structures.  The
first structure has everything except the 'text' variable, the second
structure consists of an instance of the first structure followed by a
huge text buffer.  For example:

	struct header_junk {
		int	length;
		int	other stuff;
		whatever else you need;
	};

	struct LINE {
		struct header_junk hj;
		char	text[32768]; /* or other large number */
	};

When you malloc() the structure, specify the size as
'sizeof(struct header_junk)+length' but assign the pointer to something
of type 'struct LINE'.  This has the minor drawback of adding another
level of indirection to get at the variables in the header and on some
machines (actually: some compilers) this might add to the execution
time.  This can be taken care of by using a pointer to the header area.
Note that this only adds one pointer instead of one pointer for each
line element.  You could probably even cheat a little and just use a
cast to convert the pointer to the proper type.
-- 
David H. Brierley
Raytheon Submarine Signal Division; Portsmouth RI; (401)-847-8000 x4073
smart mailer or arpanet: dhb at rayssd.ray.com
old dumb mailer or uucp: {cbosgd,gatech,ihnp4,linus!raybed2} !rayssd!dhb



More information about the Comp.lang.c mailing list