Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!ima!mirror!rayssd!dhb From: dhb@rayssd.UUCP Newsgroups: comp.lang.c Subject: Re: Auto variable with sizeof == 0 Message-ID: <655@rayssd.RAY.COM> Date: Thu, 12-Feb-87 13:06:57 EST Article-I.D.: rayssd.655 Posted: Thu Feb 12 13:06:57 1987 Date-Received: Fri, 13-Feb-87 22:46:55 EST References: <4114@brl-adm.ARPA> <4053@utcsri.UUCP> <159@batcomputer.tn.cornell.edu> Sender: dhb@rayssd.RAY.COM (David H. Brierley @ Raytheon Company, Portsmouth RI) Reply-To: dhb@rayssd.RAY.COM (David H. Brierley) Organization: Raytheon Company, Portsmouth RI Lines: 51 In article <159@batcomputer.tn.cornell.edu> braner@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@rayssd.ray.com old dumb mailer or uucp: {cbosgd,gatech,ihnp4,linus!raybed2} !rayssd!dhb