简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM