Are string literals automatic variables used inside functions? Or are they allocated to a heap that we must free manually?
I have a situation like the code below, in which I assign a string literal to a private field of the class (marked as ONE in the code) and extract it much later in my program and use it (marked as TWO). Am I assigning a variable on the stack to a field in ONE? Can the code refer to a dangling pointer that worked in this case because the program was small enough?
I compiled and ran it, it worked fine, but I have a strange crash in my real program, where I assign string literals for class fields like this, and I suspect I mentioned above.
#include <iostream>
using namespace std;
class MemoryLeak
{
private:
char *s;
public:
MemoryLeak() {}
void store()
{
s = "Storing a string";
}
char *retrieve()
{
return s;
}
};
int main()
{
MemoryLeak *obj = new MemoryLeak();
obj->store();
cout << obj->retrieve() << endl;
delete obj;
return 0;
}
Should I declare the variable "s" as a char array instead of a pointer? I plan on using std :: string, but I'm just curious.
Any pointers or help, as always, are greatly appreciated :) Thank you.
source
share