Sign in to follow this  

Memory for literal strings

This topic is 4466 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Consider: class TestClass { public: TestClass( char* Text ) : m_Text(Text) {} char* m_Text; }; TestClass* a = new TestClass( "This is the text." ); m_Text is now valid but where is the memory allocated?

Share this post


Link to post
Share on other sites
In the exe file itself. On Windows it'll be in the .data section of the file. Create a new project, instance that class in the code and compile then open the resulting exe with a hex editor and search for the text. It'll be there.

Share this post


Link to post
Share on other sites
As an aside:

If your worried about memory consumption from many string literals ---

If you find yourself using the same literal values over and over, check your compiler for what is usually refered to as "String Pooling" - sometimes the compiler names it "Read Only Strings"

If you use the string "This is a string" 50 times, some compilers will allocate each instance seperately.

char *s1 = "This is a string"
char *s2 = "This is a string"
etc...

If you never modify the data, then you can flip on string pooling, that way the string is only allocated once. It can save some space although it will usually be very little.



Share this post


Link to post
Share on other sites

This topic is 4466 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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