Search code examples
c++stdstring

VS2022: std::string.c_str() Dangling pointer warning


I am getting a dangling pointer warning from VS2022 for this code snippet:

chars = (unsigned char*)(pProgram->getProgramUUID().c_str());
memcpy(&outputBuffer[bufferPosition], chars, numChars);

Warning

Warning C26815  The pointer [chars] is dangling because it points at a temporary instance which was destroyed.

getProgramUUID() returns a std::string and is defined as

std::string getProgramUUID() { return m_programUUID; }

basically this is just a memcpy from a pointer returned by c_str().

Any idea if this is a genuine issue, or this is just VS being pedantic?

Regards, Abhishek


Solution

  • Because getProgramUUID() returns a string by value, that string object will be destructed and cease to exist once the full expression (the assignment) is finished. The pointer to the contained string will become immediately invalid.

    As a workaround you could call getProgramUUID() as part of the memcpy call:

    memcpy(&outputBuffer[bufferPosition], pProgram->getProgramUUID().c_str(), numChars);