Eric Sosman
5/15/2011 11:59:00 AM
On 5/14/2011 2:15 PM, janus wrote:
> Another thing it is likely to print is "SIGSEGV" or "SIGBUS" or
> "General Protection Fault" or something along those lines. The
> anonymous array created by the string literal is not `const', but
> that's just an accident of history. Trying to modify such an array
> yields undefined behavior -- and indeed, plenty of compilers will
> put the arrays in read-only memory. (This allows them to save space
> by allocating just one array to hold both of "over" and "recover".)
>
> I am a bit confused by the above...
It is customary to mark the material you quote, making it
distinguishable from material of your own authorship. See those
greater-than signs at the left margin? Most news clients or mail
clients will insert them for you.
It is also customary to attribute the quoted material to its
author (or authors), so that readers aren't misled into thinking
its your own. See that "On...janus wrote:" line at the top?
Again, most news clients or mail clients will insert such lines
for you.
To use the medium effectively, first learn to use the medium.
> Is the correct?
>
> char* string = "NEW";
> strcat(string, "Jersey");
Undefined behavior.
> If string is in read-only memory, could it still support things like concatenation?
No.
Nor should it. Think of it this way: A string literal (when
used this way) is notionally a constant, much like 42 or 3.14. If
you start modifying constants, things will become very confusing
very rapidly:
int i = 6;
6 *= 7; /* not legal; just imagine */
int j = 6; /* does j have the value forty-two? */
Similarly with string constants: By concatenating to a string (or
by changing one or more of its existing characters), you change
the value of that string. So:
char *message = "Hello, world!";
strcpy(message, "Go to Hell!"); /* not legal; just imagine */
puts(message); /* friendly, or confrontational? */
You don't (or shouldn't) want to change a constant, and C doesn't
promise that an attempt to do so will succeed. (Doesn't promise
anything at all about what will happen, actually.)
--
Eric Sosman
esosman@ieee-dot-org.invalid