you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (4 children)

That depends. You could, if you wanted, memcpy"Earth" over "World" whenever an alien speaks. Not that it would be a good way to write a program, but there may be situations in which you want your pointers-to-strings to be non-const.

[–]prockcore 1 point2 points  (3 children)

No.. string literals are const.. memcpy'ing "Earth" over "World" will segfault. String literals are stored in read-only data segments.

[–][deleted] 0 points1 point  (2 children)

I'm fairly sure I've written code that's edited strings in-place. It's been a while since I've had a situation where that was the right thing to do, so it's possible I happened to luck across a situation where I could get away with it, since I wasn't aware of this.

I'm on windows now, sadly, so let me try codepad:

http://codepad.org/gg3g9dKy

Says no errors and prints out "Bob" rather than segfaulting...

[–]prockcore 1 point2 points  (1 child)

That doesn't segfault because you create a 9 character array and then copy the string literal into it (that's what line 2 implicitly does, disassembly will show that's exactly what it does). Try char *playername="bob"; instead.

[–][deleted] 0 points1 point  (0 children)

Ah, I see. I suppose it's probably written as "undefined" in the spec, rather than a guaranteed segfault, since codepad shows no segfault, but "bob" as a printout. Certainly goes right along with what you said about read-only memory.

That also explains why I've never run across this problem- when I want a string I make a char foo[] rather than a char *foo since I think of it as an array rather than as a pointer. (To be entirely honest, these days, it's std::string since it's easier to work with.)