Solved

String literals in C++

Posted on 2004-09-27
3
574 Views
Last Modified: 2008-01-09
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?
0
Comment
Question by:priyendra
3 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 125 total points
ID: 12159234
1) cp points to read-only memory where program string constants are kept. Changing of this memory is access violation.
2) cp points to char aray allocated on stack. It is possible to change this memory.
3) *cp is constant pointer, *cp = ... is not allowed.
0
 

Author Comment

by:priyendra
ID: 12159385
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.
0
 
LVL 30

Expert Comment

by:Axter
ID: 12162049
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.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question