Link to home
Start Free TrialLog in
Avatar of priyendra
priyendra

asked on

String literals in C++

The following program seg faults on my machine.

int main() {
    char *cp = "Hell";
    *cp = 'B';
}

while the following works fine.

int main() {
    char cp[] = "Hell";
    *cp = 'B';
}

The following program does not compile.

int main() {
    const char *cp = "Hell";
    *cp = 'B';
}

Can someone explain the three observations?
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of priyendra
priyendra

ASKER

Alex, thanks a lot for your answer. I guess this must be one of the fastest answers I have ever obtained in EE :-) For my other question, I shall await a few more comments before closing.
Avatar of Axter
FYI:
Not all compilers will put string literals in read-only memory.

Changing the contents of a string literal results in undefined behavior IAW with the C++ standards.

Some compilers will allow you to do this, and others will not.
For example, VC++ 5.0 will allow you to change the contents of a pointer to a string literal.
However, VC++ 6.0/7.x will not.


You should avoid code that results in undefined behavior.