最近,我在以下代码中发现了该漏洞:
ostringstream o;
o << "some string";
const char* s = o.str().c_str(); // empty string instead of expected "some string"这是由cppreference.com:解释的。str返回的基础字符串的副本是一个临时对象,它将在表达式的末尾被解构,因此直接对str()的结果调用c_str() (例如,在auto *ptr = out.str().c_str();)中,会导致一个悬空指针。
修复这个bug没有任何问题,但是,我在项目中有很多地方,如下所示:
ostringstream o;
o << "error description";
throw my_exception(o.str().c_str());
...
my_exception::my_exception(const char* s) :
message(s) // message is std::string
{}这段代码是否有未定义的行为,比如第一个代码片段?
发布于 2015-12-22 09:02:48
不,消息是std::string,因此在这一点上获取char缓冲区内容的副本。
临时用于调用它的函数的作用域-在本例中是构造函数。
https://stackoverflow.com/questions/34411874
复制相似问题