V
Victor Bazarov
Ney said:The following is a summary of what I have understood from reading
Stroustrup's TCPL 3rd Edition's discourse on "string literals" (5.2.2).
String literals are of type const char[n], where n is the length of the
literal plus one. However, for compatibility reasons, assignment of such
a literal to a non-const char* is allowed, e.g.:
char* name = "Ney Zunino";
In spite of that assignment being allowed, it is not permitted to use
that pointer to modify the string literal. Next, Stroustrup adds that
this kind of error cannot generally be caught until runtime. As a matter
of fact, that's precisely what I have experienced with the following
test program:
int main()
{
char* s = "Ney André de Mello Zunino";
s[2] = 'i';
}
Both Microsoft Visual C++ 2003 and g++ 3.3.3 compiled it quietly and
both executables caused protection faults at runtime. Fine, it all went
just like Stroustrup had said, but what I don't understand is why. Why
is it so hard for a compiler to catch such violation? Isn't it clear
that the address assigned to 's' was that of a statically-allocated
literal?
Why bother catching it if the Standard doesn't require catching it? The
fact that you're trying to modify a literal becomes much less clear if
you pass the pointer into another function which will modify the contents
and even less clear if that function is in another translation unit. So,
instead of requiring the implementations to watch out for those, the C++
Standard simply says that an attempt to modify leads to undefined
behavoiur. It's up to you as a programmer to prevent it. There are tools
that go the extra mile to try to fish out those mistakes. Are they good?
Those who use them can probably tell. I don't use them. I simply don't
write code like in your example.
V