Hello.
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?
Thank you for your comments,
--
Ney André de Mello Zunino