Sign in to follow this  
zyrolasting

[C++] Reliability of string literals

Recommended Posts

zyrolasting    280
I'm surprised I don't already know this, but when assigning a string literal to a char*, can I rely on it to persist in the same location in memory over time? If not, what about with dynamic memory?

Share this post


Link to post
Share on other sites
How it works varies by compiler, but it will not suddenly change behind your back. Don't expect it to be the same each time you run a program or if you assign it one time to a variable which goes out of scope, and again to another one, such as if it gets assigned to a local variable every time a method gets called.

Share this post


Link to post
Share on other sites
zyrolasting    280
Well, I'm making a data-driven model for my project and I'm using a union containing a double and char*. When I dereference the char*, all I care about is that the content I end up getting does not change.

In YoYoGames' Game Maker, char* passed to DLLs you write and store can actually have the underlying content change when you dereference it in another routine. Hence my concern.

Share this post


Link to post
Share on other sites
phresnel    953
Actually, assigning string literals to char* is deprecated and non-standard C++:

Quote:
2.13.4/1 [lex.string]
An ordinary string literal has type “array of n const char” and static storage duration (3.7)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this