1

In the following code, temporary string object is created and destroyed after returning its internal buffer. Therefore p points to an invalid memory location.

int main()
{
    const char* p = std::string("testing").c_str();
    //p points to an invalid memory location
}

In the following code, temporary string object is created. When is the tempory string object get deleted? After or before executing func()? Can I safely use the p pointer inside the func() method?

void func(const char* p)
{
    //p is valid or invalid ????
}

int main()
{
    func(std::string("testing").c_str());
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
SRF
  • 929
  • 1
  • 7
  • 15

1 Answers1

1

p is valid until immediately after the statement func(std::string("testing").c_str());. That means that the anonymous temporary string is not popped from the stack until after func has returned.

So your code is completely safe.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483