Tech Journal Back to Tech Journal

C Riddle: The read-only-ness of string constants

Question: Can you write to the areas in memory that hold string constants?

As part of the C language specification, the compiler is allowed to assign whatever location is pleases to string constants. It isn't even required to store seperate copies for identicle string constants. So a piece of code like this:

char *s = "hello";
s[0] = 'H';

s is a pointer to a string constant, and trying to write to the memory it points to will result in a very compiler-dependant outcome. Some compilers (such as GCC) will place string constants inside read-only memory, in which case the above write will raise an exception (usually a Segmentation Fault.) Other compilers may very well place the same string constant in a read-write area, and not fail at all. My personal favorites are those that detect such a write, and give a warning. But even those same warnings can be supressed by use of a judicous cast. Like:

*(char**)(&s)

Since the &s is an lvalue, the compiler doesn't really care what is done with it... Actually, that same type of cast works for writing to const-cast variables or function arguments.

Last updated on 2005-08-02 14:00:00 -0700, by Shalom Craimer

Back to Tech Journal