Deutsch   English   Français   Italiano  
<v8gte2$2ceis$2@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!.POSTED!not-for-mail
From: Bart <bc@freeuk.com>
Newsgroups: comp.lang.c
Subject: Re: relearning C: why does an in-place change to a char* segfault?
Date: Thu, 1 Aug 2024 22:07:16 +0100
Organization: A noiseless patient Spider
Lines: 48
Message-ID: <v8gte2$2ceis$2@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>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Thu, 01 Aug 2024 23:07:15 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="1e1bbde09af84609d5b2b26e972c5153";
	logging-data="2505308"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1+e620hsMMAB/NcyaTRae3r"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:DF5spvzQpz8ahMg/5o2cACi2TfE=
Content-Language: en-GB
In-Reply-To: <87jzh0gdru.fsf@nosuchdomain.example.com>
Bytes: 2736

On 01/08/2024 21:59, Keith Thompson wrote:
> Bart <bc@freeuk.com> writes:
>> On 01/08/2024 09:38, Richard Harnden wrote:
>>> On 01/08/2024 09:06, Mark Summerfield wrote:
>>>> This program segfaults at the commented line:
>>>>
>>>> #include <ctype.h>
>>>> #include <stdio.h>
>>>>
>>>> void uppercase_ascii(char *s) {
>>>>       while (*s) {
>>>>           *s = toupper(*s); // SEGFAULT
>>>>           s++;
>>>>       }
>>>> }
>>>>
>>>> int main() {
>>>>       char* text = "this is a test";
>>>>       printf("before [%s]\n", text);
>>>>       uppercase_ascii(text);
>>>>       printf("after  [%s]\n", text);
>>>> }
>>> text is pointing to "this is a test" - and that is stored in the
>>> program binary and that's why can't modify it.
>>
>> That's not the reason for the segfault in this case.
> 
> I'm fairly sure it is.
> 
>>                                                       With some
>> 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};

Do these not also have static storage duration? Yet presumably these can 
be legally modified.