内存分配错误处理不当¶
ID: cpp/incorrect-allocation-error-handling
Kind: problem
Security severity: 7.5
Severity: warning
Precision: medium
Tags:
- correctness
- security
- external/cwe/cwe-570
- external/cwe/cwe-252
- external/cwe/cwe-755
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
new
运算符的不同重载以不同的方式处理分配失败。如果对某种类型 T
的 new T
失败,它将抛出 std::bad_alloc
异常,但 new(std::nothrow) T
返回一个空指针。如果程序员没有使用相应的错误处理方法,分配失败可能得不到处理,并可能导致程序以意想不到的方式运行。
建议¶
如果使用 new T
,请确保适当地处理异常。另一方面,如果使用 new(std::nothrow) T
,请确保处理空指针的可能性。
示例¶
// BAD: the allocation will throw an unhandled exception
// instead of returning a null pointer.
void bad1(std::size_t length) noexcept {
int* dest = new int[length];
if(!dest) {
return;
}
std::memset(dest, 0, length);
// ...
}
// BAD: the allocation won't throw an exception, but
// instead return a null pointer.
void bad2(std::size_t length) noexcept {
try {
int* dest = new(std::nothrow) int[length];
std::memset(dest, 0, length);
// ...
} catch(std::bad_alloc&) {
// ...
}
}
// GOOD: the allocation failure is handled appropriately.
void good1(std::size_t length) noexcept {
try {
int* dest = new int[length];
std::memset(dest, 0, length);
// ...
} catch(std::bad_alloc&) {
// ...
}
}
// GOOD: the allocation failure is handled appropriately.
void good2(std::size_t length) noexcept {
int* dest = new int[length];
if(!dest) {
return;
}
std::memset(dest, 0, length);
// ...
}
参考资料¶
CERT C++ 编码标准:MEM52-CPP. 检测和处理内存分配错误.
通用弱点枚举:CWE-570.
通用弱点枚举:CWE-252.
通用弱点枚举:CWE-755.