Deutsch   English   Français   Italiano  
<vo9nn3$gtph$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail
From: Andrey Tarasevich <noone@noone.net>
Newsgroups: comp.lang.c
Subject: Re: Two questions on arrays with size defined by variables
Date: Sun, 9 Feb 2025 00:06:56 -0800
Organization: A noiseless patient Spider
Lines: 60
Message-ID: <vo9nn3$gtph$1@dont-email.me>
References: <vo9mns$gsd7$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Sun, 09 Feb 2025 09:07:00 +0100 (CET)
Injection-Info: dont-email.me; posting-host="b46cc674ba558476b6b694ab42c1b417";
	logging-data="554801"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18gQQATTg4md9lNMP9Qe0JI"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:pzsyMOvWhX5Ov1IRwLIoJKFLo/4=
In-Reply-To: <vo9mns$gsd7$1@dont-email.me>
Content-Language: en-US
Bytes: 2959

On Sat 2/8/2025 11:50 PM, Janis Papanagnou wrote:
> I've found examples on the Net where the arrays have been defined in a
> function context and the size passed as parameter
> 
>    f(int n) {
>       char * arr[n];
>       ...
>    }

Yes, that would be a VLA.

> That reminded me on other languages where you'd need at least a block
> context for dynamically sized arrays, like
> 
>    int n = 5;
>    {
>       char * arr[n];
>       ...
>    }

But a function body is in itself a block. Inside a function body you are 
already in "a block context".

> Anyway. I tried it without function or block context
> 
>    int n = 5;
>    char * arr[n];
>    ...
> 
> and it seemed to work seamlessly like that (with GNU cc, -std=C99).

You mean you did this at file scope? No, VLAs are illegal at file scope. 
And I was unable to repeat this feat in GCC.

> Q1: Is this a correct (portable) form?

VLA objects have to be declared locally. However, keep in mind that 
support for local declarations of VLA _objects_ is now optional (i.e. 
not portable). Support for variably-modified _types_ themselves (VLA 
types) is mandatory. But you are not guaranteed to be able to declare an 
actual VLA variable.

> Then, with above setting, I also tried
> 
>    arr[99] = "foobar";
> 
> To my astonishment the compiler did not only accept that but it also
> operated without runtime error; but I assume it's an error that may
> severely corrupt the memory. - Q2: Is my suspicion correct?

Yes. Since the beginning of times the language itself does not 
check/enforce array boundaries. When you violate the boundary, the 
behavior is undefined, meaning that compilers can do anything (including 
implementing array boundary checks, where possible). But for obvious 
performance reasons C compilers do not normally enforce array boundaries 
in "production" compilation modes.

-- 
Best regards,
Andrey