Zero Length Arrays Allowed in C Standard?

Liam R. E. Quin lee at sq.sq.com
Wed Dec 13 14:35:16 AEST 1989


davidsen at crdos1.crd.ge.COM (Wm E Davidsen Jr) writes:
> gsf at ulysses.homer.nj.att.com (Glenn Fowler[drew]) writes:

>| why not make the last element huge rather than small and then at malloc time
>| decrease the sizeof rather than increase: [...]

You can only do that with malloc, of course, and that sounds to me to be
even more dangerous!

>  It has one advantage over the use of size zero or one: if you have a
>compiler which checks subscripts (I haven't seen one, but Sabre might)
>this will allow subscripts up to the max range.

Sabre-C checks bounds on both statically defined arrays (declared with
	t_SomeType ArrayName[ArraySize];
or whatever) and also on malloc'd areas of memory
	char *p = malloc( (unsigned) (BUFSIZ + 1));

It also reports references to data (including array elements) before they
have been initialised.
The tests are a little simplistic, involving initialising things with a
magic number (which you can set), but they are robust enough to be useful.

You can turn off the array- and malloc-checking if you want; although I
don't remember if you can do so on a per-variable basis, you can on a per-
file basis.

I have no idea what Sabre-C does with zero sized arrays.  The Sun with
Sabre on it isn't here right now (!) so I can't check.


Seeing as I've posted into this argume -- er, discussion,...

Yes, I sometimes use structures whose last element is of type char[1] so that
I can later malloc  larger lump.  Every time I do this (including in the
text retrieval package I sent to comp.sources.unix), I debate between doing
this and using a pointer, which I can set to point just beyond the structure
in the same allocated space.
I find that the [1] trick is a little simpler, and I am less likely to call
free() on the pointer by mistake in my "destructor function" that frees a
structure.

>#define getstructx(size) \
>  (struct whatever *)malloc(sizeof(struct whatever)+size)

I prefer *not* to do this, because if there are problems with the technique,
porting will involve more than simply changing this macro.  Some things are
better hidden, and soe are not, I think.
-- 
Liam R. Quin, Unixsys (UK) Ltd [note: not an employee of "sq" - a visitor!]
lee at sq.com (Whilst visiting Canada from England, until Christmas)
 -- I think I'm going to come out at last...
 -- What?  Admit you're not a fundamentalist Jew?  They'll *crucify* you!  :-)



More information about the Comp.lang.c mailing list