0

Possible Duplicate:
Modifying C string constants?

As far as I understand if you want to make a c string constant you should give a declaration like :

const char* str = "hello";

or

char* const str = "hello";    

But a simple declaration like:

char* str = "hello"

If I try to modify the string by any means - like

str[2] = 'f';

or

*(str+2) = 'f';

I always get a segmentation fault, why is that ?

Also if I do a declaration like

const char* const str = "hello";
str = "bye";  

as per scott meyers I am trying to modify a const pointer and should get warning, error or segfault, but I get nothing and code compiles and executes perfectly. I am puzzled, I am using g++ on ubuntu 11.10.

Community
  • 1
  • 1
ocwirk
  • 1,079
  • 1
  • 15
  • 35
  • Yes, I'm puzzled, too. Any conforming compiler should reject the last snippet of code shown. If yours doesn't, it contains a bug. Before blaming the compiler, ensure that you're not ignoring any warnings. – Cody Gray - on strike Jan 25 '12 at 03:29
  • *The code compiles and executes properly* because modifying a string literal results in an **Undefined Behavior** which means all safe bets are off,your program might work or might crash or show any weird behavior.An Undefined Behavior implies that the program is ill-formed and can show a behavior which may or may not be explained. – Alok Save Jan 25 '12 at 03:29

2 Answers2

4
char* str = "hello"

This makes use of a deprecated conversion that allows a string literal to be implicitly converted to a char*. Do not make use of this conversion.

The characters in the string literal are still const, despite the fact that you are making str point to the string literal.

const char* const str = "hello";
str = "bye"; 

This code is ill-formed. Your compiler should reject it.

If your compiler does not reject this code or does not at least issue a diagnostic message (warning), it is either a bug in the compiler or a "language extension."

James McNellis
  • 348,265
  • 75
  • 913
  • 977
3
char* str = "hello";

String literal hello resides in read only location and cannot be modified. Compiler should emit a warning regarding the initialization of identifier str.

To actually modify the string, you need to do -

char str[] = "hello"; // Copying the string literal hello to the array str

str[2] = 'f';  // Now these are valid.
str[2] = 'f';
Mahesh
  • 34,573
  • 20
  • 89
  • 115