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?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER