Reputation: 893
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
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 char
s will not work. If that is what you want, then use arrays of char
s.
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
Reputation: 10393
String literals have static storage duration, so they exist for the entire duration of program execution.
Upvotes: 2
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