sizeof(array) with variable-length array parameter

peter.kourzanov@xs4all.nl peter.kourzanov@xs4all.nl
Wed Apr 9 16:17:00 GMT 2008


On Wed, Apr 09, 2008 at 01:22:15PM +0100, Andrew Haley wrote:
> peter.kourzanov@xs4all.nl wrote:
> > Dear gcc users and developers, 
> > 
> >   This might be a stupid question, nevertheless...
> > 
> >   I've been wondering for a long time, why the behaviour of
> > variable-length arrays w.r.t. the sizeof operator is different
> > for local/auto variables and for function arguments (in C99):
> > 
> > #include <stdio.h>
> > void foo(int s, int a[s]) {
> >         printf("%u\n",sizeof a);
> > }
> > int main()
> > {
> >         int s=10,a[s];
> >         printf("%u\n",sizeof a);
> >         foo(sizeof a/sizeof a[0],a);
> > }
> > 
> >   The printf's produce very different results: the first one
> > returns "40" the other one returns 4, implying that the compiler
> > forgets that the size of the array is actually "s", not the size
> > of the pointer argument. Is it so difficult to make "sizeof a" 
> > return "s" in both cases?
> 
> That's C for you, I'm afraid: arrays always decay to pointers to the
> first element when passed as arguments.  The size of a VLA is not passed.


  Well, it sort of is: it is actually passed as a parameter to the
function - look at the C99 defining a syntax for VLA parameters.
The fact the the compiler forgets about it could be compensated by
this...

  What I would like to know, is why the standard (ISO/IEC 9899) does
explicitly require sizeof to return size of the pointer rather than
more obvious response? Is it backwards compatibility? 

  Is there any use in this behaviour besides making the life of
the compiler development team easy?

  Surely, such an extension should be not too difficult to implement,
provided that the compiler can account for (potential) modifications
to the size parameter and require sizeof the return the value that
was actually passed to the function, which BTW, it already does,
since this behaviour is easily verified to work well for variable
VLAs.

  In fact, strictly following C99 standard would force one that is
not familiar with the use of const on integer parameters to use
the "s" parameter to retrieve the size, which could lead to subtle
bugs if the parameter is modified on the way:

void foo(int s, int a[s]) {
	 s=20;
         printf("%u\n",s);
}

  Also, making sure that there are no out-of-bounds accesses
(mudflap) is simply impossible if the array size is not known...

Just curious...
  
Pjotr

> 
> Andrew.
> 



More information about the Gcc-help mailing list