Sujet : Re: relearning C: why does an in-place change to a char* segfault?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 01. Aug 2024, 22:13:32
Autres entêtes
Organisation : None to speak of
Message-ID : <87bk2cgd4z.fsf@nosuchdomain.example.com>
References : 1 2 3
User-Agent : Gnus/5.13 (Gnus v5.13)
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.comvoid Void(void) { Void(); } /* The recursive call of the void */