Solved

String literals in C++

Posted on 2004-09-27
3
545 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall‚Ķ
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 clear a vector as well as how to detect empty vectors in C++.

757 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now