Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string dynamically allocated?

Tags:

c++

string

I have got a quick question. I have the following code:

class Class1
{
    Class1();
    ~Class1();
    void func1();
private:
    char* c;

}

void Class1::func1()
{
    string s = "something";
    this->c = s.c_str();
}

will c store "something" when func1() finishes?

like image 906
DalekSupreme Avatar asked Dec 29 '25 16:12

DalekSupreme


2 Answers

No. It will invoke undefined behavior instead. (if you dereference the pointer, anyway.) Since s is a block-scope object with automatic storage duration, it is destroyed when the function returns, and that renders the pointer returned by .c_str() invalid.


Why not use an std::string member variable instead?

s is a local variable of type std::string in Class::func1. Once func1() finishes, the string s will go out of scope.

Any pointers you have with the address of s stored in them will become dangling pointers.

like image 35
digital_revenant Avatar answered Dec 31 '25 09:12

digital_revenant