Deutsch English Français Italiano |
<87bk2cgd4z.fsf@nosuchdomain.example.com> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!2.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson <Keith.S.Thompson+u@gmail.com> Newsgroups: comp.lang.c Subject: Re: relearning C: why does an in-place change to a char* segfault? Date: Thu, 01 Aug 2024 14:13:32 -0700 Organization: None to speak of Lines: 54 Message-ID: <87bk2cgd4z.fsf@nosuchdomain.example.com> References: <IoGcndcJ1Zm83zb7nZ2dnZfqnPWdnZ2d@brightview.co.uk> <20240801114615.906@kylheku.com> <v8gs06$2ceis$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Thu, 01 Aug 2024 23:13:32 +0200 (CEST) Injection-Info: dont-email.me; posting-host="933b865835dd2da7485caeddca825875"; logging-data="2515784"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18sp57ii4FefKeqihFyeWcB" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:8gaSFguuR0ZY3hfw4xqGEeddQUw= sha1:XY1FBGDRgcaR3RNQTJQQcUeS8jU= Bytes: 2727 Bart <bc@freeuk.com> writes: > On 01/08/2024 20:39, Kaz Kylheku wrote: >> On 2024-08-01, Mark Summerfield <mark@qtrac.eu> 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"; >> The "this is a test" object is a literal. It is part of the >> program's image. > > So is the text here: > > char text[]="this is a test"; > > But this can be changed without making the program self-modifying. Incorrect. The string literal results in the creation of an array object. Any attempt to modify that array object would have undefined behavior -- but there's no way to modify it because its address isn't available to the code. `text` is a distinct object. At execution time (assuming it's defined at block scope), that object is initialized by copying from the string literal object. (This is what happens in the abstract machine; there are opportunities for optimization that might result in the string literal object not existing in the generated code.) > I guess it depends on what is classed as the program's 'image'. Not really. Given: int n = 42; you can't modify 42, but you can modify n. There's no need to consider the idea of self-modifying code. You're just trying to make it seem more confusing than it really is. [...] -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com void Void(void) { Void(); } /* The recursive call of the void */