Auto variable with sizeof == 0

pinkas at mipos3.UUCP pinkas at mipos3.UUCP
Tue Feb 3 02:51:56 AEST 1987


In article <4114 at brl-adm.ARPA> escott%deis.uci.edu at icsg.uci.edu (Scott Menter) writes:
>				... I found a construct that
>seems a little strange to me: an automatic variable was declared as a
>"struct foo **bar[]".  "How could this be right?"  I said to myself.  "How
>can you declare an automatic variable that has no size?"
>
>So I wrote a program that contained a similar declaration, and then tried to
>take sizeof( bar ).  Sure enough:
>
>	warning: sizeof returns 0
>
>[This from the VAX 11/750 4.2BSD compiler]
>
>Okay, that makes sense.  My question is: is there any reason why you should
>be able to declare an array with zero elements as an automatic variable?
>What's strange is that, on the VAX, the program apparently successfully
>dereferenced bar, both setting a value for "*bar" and then using that value
>later.  How can this be right?  How can "bar" have any value at all, much
>less "*bar"?  If there is no use for a zero-sized automatic variable, how
>come the compiler lets you do it?

I don't see the problem with this declaration.  bar is declared to be an
array of pointers to pointers to struct foo.  That is, **(bar[0]) is of
type foo.  bar initially has no memory allocated to it.  This type of
construct appears to be a dynamic array, where malloc will be called to get
some memory.  Since the array is declared to have zero elements, sizeof
will return zero.  (Remember that sizeof(array) =~ sizeof(element of array)
times number of elements.  This is approximate because C allows a compiler
to pack arrays.)  So in your case, the compiler was correct in warning you
that bar was of size zero (taking sizeof a zero sized element is not very
useful as the most common uses for sizeof are malloc and pointer arithmatic
when something cast the pointer to a different type).  You should inspect
the code, but if it worked on one machine, it should work on another.  It
could be that they really wanted to say sizeof(foo), in something like:

	bar = malloc(sizeof(struct foo) * 100)

which would allocate 100 elements to the array bar, making it the
equivalent of the auto declaration struct foo **bar[100].

-Israel
-- 
----------------------------------------------------------------------
UUCP:	{amdcad,decwrl,hplabs,oliveb,pur-ee,qantel}!intelca!mipos3!pinkas
ARPA:	pinkas%mipos3.intel.com at relay.cs.net
CSNET:	pinkas%mipos3.intel.com



More information about the Comp.lang.c mailing list