Keith M
Keith M

Reputation: 893

Is setting a const char* equal to a char[] literal safe?

I found this in some C++ code:

const char *scaryPointer = "literal";

To my surprise, this doesn't generate a compiler warning or error (at least in Visual Studio 2008).

Is this actually safe to do? I thought that the address of the char[] literal would be invalid after that line is finished executing.

If it's safe, what happens if you reassign scaryPointer to a new literal? The address of the old literal gets automatically freed then? Automatic garbage collection?

I found this question, but (I think) the questions/answers don't fully address my question & concerns.

Upvotes: 0

Views: 459

Answers (3)

PointerToConstantChar
PointerToConstantChar

Reputation: 146

const char *notScaryPointer = "literal"; is perfectly valid C. It is a pointer to a char in read only memory. You can later reassign it like notScaryPointer = "some_other_literal";. But because const char*s assigned to a string literal live in read-only memory, You can't change them. For example. This code snippet will probably give you a runtime error:
const char* strPointer = "Hello, world!"; strPointer[0] = 'Y';

If you want mutable strings, Then pointers to chars will not work. If that is what you want, then use arrays of chars.

Edit: I didn't notice what you were asking at first, But as others have pointed out, String literals have static storage duration.

Upvotes: 2

Joseph Thomson
Joseph Thomson

Reputation: 10393

String literals have static storage duration, so they exist for the entire duration of program execution.

Upvotes: 2

Chris Dodd
Chris Dodd

Reputation: 126203

String literals have static storage duration -- so they live as long as the program is running. They're generally stored in the read-only program image that is loaded when the program starts.

Upvotes: 7

Related Questions