Sujet : Re: relearning C: why does an in-place change to a char* segfault?
De : vir.campestris (at) *nospam* invalid.invalid (Vir Campestris)
Groupes : comp.lang.cDate : 13. Aug 2024, 15:34:19
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v9fqtb$3t7ph$4@dont-email.me>
References : 1 2 3 4 5
User-Agent : Mozilla Thunderbird
On 12/08/2024 22:11, Tim Rentsch wrote:
Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
[...]
A string literal creates an array object with static storage
duration. [...]
A small quibble. Every string literal does sit in an array,
but it might not be a _new_ array, because different string
literals are allowed to overlap as long as the bytes in the
overlapping arrays have the right values.
And this is exactly why string literals should always have been const.
A compiler is entitled to share memory between strings. so
puts("lap");
puts("overlap");
it's entitled to make them overlap. Then add
char * p = "lap";
*p='X';
and it can overwrite the shared string. I think. which would mean that writing "lap" again would have a different result.
But that ship has sailed. I'm not even sure const had been invented that far back!
Andy