Re: [PATCH] Various pages: SYNOPSIS: Use VLA syntax in function parameters

Uecker, Martin
2022-11-29T15:22:06Z

Am Dienstag, dem 29.11.2022 um 14:58 +0000 schrieb Michael Matz:
> Hey,
>
> On Tue, 29 Nov 2022, Alex Colomar via Gcc wrote:
>
> > How about the compiler parsing the parameter list twice?
>
> This _is_ unbounded look-ahead.  You could avoid this by using "."
> for
> your new syntax.  Use something unambiguous that can't be confused
> with
> other syntactic elements, e.g. with a different punctuator like '@'
> or the
> like.  But I'm generally doubtful of this whole feature within C
> itself.
> It serves a purpose in documentation, so in man-pages it seems fine
> enough
> (but then still could use a different puncuator to not be confusable
> with
> C syntax).
>
> But within C it still can only serve a documentation purpose as no
> checking could be performed without also changes in how e.g. arrays
> are
> represented (they always would need to come with a size).

It does not require any changes on how arrays are represented.

As part of VM-types the size becomes part of the type and this
can be used for static or dynamic analysis, e.g. you can
- today - get a run-time bounds violation with the sanitizer:

void foo(int n, char (*buf)[n])
{
(*buf)[n] = 1;
}

int main()
{
char buf[10];
foo(10, &buf);
}

https://godbolt.org/z/WWEdeYchs

I personally find this already extremely useful.

For

void foo(int n, char buf[n]);

it semantically has no meaning according to the C standard,
but a compiler could still warn.

It could also warn for

void foo(int n, char buf[n]);

int main()
{
char buf[9];
foo(buf);
}

if the passed buffer is too short. And here, GCC and Clang
already do this! (although - so far - only for static
bounds I think)

https://godbolt.org/z/afPhnxfzx

With "static"

void foo(int n, char buf[static n]);

this would also be UB according to C.

We miss some features in GCC to make this more useful (and
I filed bugs a while ago). For example, UB sanitzer should detect
additional cases which are UB.

But in general: This feature is useful not only for documentation
but also for analysis. You can get bounds checking in C which
works today and with additional compiler features this would
be very useful!

Martin

> It seems
> doubtful to introduce completely new and ambiguous syntax with all
> the
> problems Joseph lists just in order to be able to write documentation
> when
> there's a perfectly fine method to do so: comments.