Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?
I’ve a situation like the code shown below wherein I’m assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?
I’ve compiled and ran it, it worked fine but I’m having a strange crash in my actual program where I’m assigning string literals to fields of the class like this and I suspect the case I mentioned above.
#include <iostream> using namespace std; class MemoryLeak { private: char *s; public: MemoryLeak() {} void store() { s = 'Storing a string'; // ONE } char *retrieve() { return s; } }; int main() { MemoryLeak *obj = new MemoryLeak(); obj->store(); cout << obj->retrieve() << endl; // TWO delete obj; return 0; }
Should I be declaring the variable ‘s’ as a char array instead of a pointer? I’m planning to use std::string, but I’m just curious about this.
Any pointers or help is, as always, much appreciated 🙂 Thanks.
String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you’re going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.