Memory for literal strings

Started by
1 comment, last by Abbacabba 18 years, 5 months ago
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?
Advertisement
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.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
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.



This topic is closed to new replies.

Advertisement