在生命周期结束后使用唯一指针¶
ID: cpp/use-of-unique-pointer-after-lifetime-ends
Kind: problem
Security severity: 8.8
Severity: warning
Precision: high
Tags:
- reliability
- security
- external/cwe/cwe-416
- external/cwe/cwe-664
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
对 std::unique_ptr
对象调用 get
会返回一个指向底部分配的指针。当 std::unique_ptr
对象被销毁时,get
返回的指针将不再有效。如果在 std::unique_ptr
对象被销毁后使用该指针,则行为未定义。
建议¶
确保 get
返回的指针不会超出底层 std::unique_ptr
对象的生命周期。
示例¶
以下示例获取一个 std::unique_ptr
对象,然后使用 get
将生成的唯一指针转换为指针,以便可以将其传递给 work
函数。但是,std::unique_ptr
对象会在对 get
的调用返回后立即被销毁。这意味着 work
被赋予了一个指向无效内存的指针。
#include <memory>
std::unique_ptr<T> getUniquePointer();
void work(const T*);
// BAD: the unique pointer is deallocated when `get` returns. So `work`
// is given a pointer to invalid memory.
void work_with_unique_ptr_bad() {
const T* combined_string = getUniquePointer().get();
work(combined_string);
}
以下示例通过确保对 get
的调用返回的指针不会超出底层 std::unique_ptr
对象的生命周期来修复上述代码。这确保传递给 work
的指针指向有效的内存。
#include <memory>
std::unique_ptr<T> getUniquePointer();
void work(const T*);
// GOOD: the unique pointer outlives the call to `work`. So the pointer
// obtainted from `get` is valid.
void work_with_unique_ptr_good() {
auto combined_string = getUniquePointer();
work(combined_string.get());
}