Deutsch   English   Français   Italiano  
<v8h8os$2erbn$1@dont-email.me>

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

Path: ...!news.misty.com!2.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: James Kuyper <jameskuyper@alumni.caltech.edu>
Newsgroups: comp.lang.c
Subject: Re: relearning C: why does an in-place change to a char* segfault?
Date: Thu, 1 Aug 2024 20:20:43 -0400
Organization: A noiseless patient Spider
Lines: 35
Message-ID: <v8h8os$2erbn$1@dont-email.me>
References: <IoGcndcJ1Zm83zb7nZ2dnZfqnPWdnZ2d@brightview.co.uk>
 <v8fhhl$232oi$1@dont-email.me> <v8fn2u$243nb$1@dont-email.me>
 <87jzh0gdru.fsf@nosuchdomain.example.com> <v8gte2$2ceis$2@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
Injection-Date: Fri, 02 Aug 2024 02:20:59 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="fc09beaaa05891c9bcdd65835817b51b";
	logging-data="2583927"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX19+MPhcGLUmkHMi43txWjs65NK5w1+rtxc="
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:czuOm7ATmr/J5VOCoKQGsC7ExHg=
In-Reply-To: <v8gte2$2ceis$2@dont-email.me>
Content-Language: en-US
Bytes: 2837

Bart <bc@freeuk.com> writes:
> On 01/08/2024 21:59, Keith Thompson wrote:
>> Bart <bc@freeuk.com> writes:
....
>>> compilers, you *can* modify it, but that will permanently modify that
>>> string constant. (If the code is repeated, the text is already in
>>> capitals the second time around.)
>>>
>>> It segfaults when the string is stored in a read-only part of the binary.
>> A string literal creates an array object with static storage
>> duration.
>> Any attempt to modify that array object has undefined behavior.
>
> What's the difference between such an object, and an array like one of
> these:
>
>  static char A[100];
>  static char B[100]={1};

The difference is that when 6.4.5p7 says ""... If the program attempts
to modify such an array, the behavior is undefined.", it is not talking
about arrays with static storage duration in general, but only
specifically about the arrays with static storage duration that are
created to store the contents of string literals.

For other arrays, whether or not it is defined behavior to modify them
depends upon whether or not the array's definition is const-qualified.
The arrays associated with string literals should have been specified as
const-qualified, in which case any code that put them at risk of being
modified would have required either a cast or a diagnostic.

In C++ string literals are const-qualified, but "const" was a late
addition to C, and by the time it was added to C, the committee's desire
to ensure backwards compatibility prevented doing so in what would
otherwise have been the most reasonable way.