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 : 13. Aug 2024, 21:08:16
Autres entêtes
Organisation : None to speak of
Message-ID : <8734n8gp8v.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6
User-Agent : Gnus/5.13 (Gnus v5.13)
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.
>
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!
The reason that *wasn't* done is that it would have broken existing
code.
In pre-ANSI C, "const" didn't exist, and this:
char *ptr = "hello";
was the only way to create a pointer into a string literal object.
Making string literals const would have broken such code, with no clean
way to rewrite it so it would be accepted by old and new compilers.
I suppose you could do something like:
#ifndef __STDC__
#define const
#endif
In 20/20 hindsight, my personal opinion is that it would have been
better to make string literals const in C89/C90. Compilers could
still accept old const-incorrect code with a non-fatal warning,
and programmers would be encouraged but not immediately forced to
use const.
This could still be done in C2y, but I'm not aware of any proposals.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */