Sujet : Re: relearning C: why does an in-place change to a char* segfault?
De : jameskuyper (at) *nospam* alumni.caltech.edu (James Kuyper)
Groupes : comp.lang.cDate : 02. Aug 2024, 01:20:43
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v8h8os$2erbn$1@dont-email.me>
References : 1 2 3 4 5
User-Agent : Mozilla Thunderbird
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.