Sujet : Re: relearning C: why does an in-place change to a char* segfault?
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 14. Aug 2024, 01:40:24
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86h6boszrb.fsf@linuxsc.com>
References : 1 2 3 4 5 6
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Vir Campestris <
vir.campestris@invalid.invalid> writes:
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.
The people who wrote the C standard reached a different
conclusion, and IMO the right one.
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.
A C implementation is also allowed to put every string literal
in its own separate array object, not shared even when two
or more string literals are identical, and make them writable
so they can be modified without problems. I believe some C
compilers actually did this, perhaps under the control of a
compilation option.
But that ship has sailed. I'm not even sure const had been
invented that far back!
C was already well established before 'const' was invented, and it
was a number of years after that before some C compilers started
allowing 'const' in source code. The cost of not being backward
compatible would be high; the cost adding const incrementally in
new code is low. Generally speaking using string literals in open
code is a bad idea anyway, regardless whether there is any concern
that the string might be modified. I think most people who want
string literals to be of type const char[] are only thinking about
one side of the equation. It's always important to remember to
look at both sides of the cost/benefit forces, and not focus on
just the (imagined) benefits or (imagined) downsides.