我的 delete[] 有什么问题?
What is wrong with my delete[]?
我总是用 delete[]
删除数组。但是 HP Fortify 显示 Memory Leak。我的代码有什么问题?
unsigned buflen = SapUcConverter::getFormatBufferLength(len);
char* buffer = new char[buflen]; // Here is the memory leak marked by Fortify
if(valueCanBeLogged) {
LOGMSG(_DBUG, "nameForLog=%s, len=%d, sapuc='%.*s'",
nameForLog, len, buflen,
SapUcConverter::format(buffer, sapuc, len));
} else {
LOGMSG(_DBUG, "nameForLog=%s, len=#####, sapuc=#####");
}
delete[] buffer;
如果SapUcConverter::format
或任何在LOGMSG
展开时可能调用的函数(假设是宏)不声明noexcept
, then as far as the code that calls them knows, they may throw. And if they do, then buffer
leaks. Solution: Adhere to RAII原则。 RAII 的最简单方法是使用 std::vector
或 std::string
.
SapUcConverter::format() is a long function for building a logging string. There is no throw in it.
仅仅因为没有 throw
表达式,并不意味着它不能抛出。听起来它可能会分配动态内存。 new
表达式可以抛出。附加到 std::string
可能会抛出。但是,如果您 100% 认为 SapUcConverter::format
中的任何表达式都不会抛出,那么您可以使用 noexcept 说明符。
我总是用 delete[]
删除数组。但是 HP Fortify 显示 Memory Leak。我的代码有什么问题?
unsigned buflen = SapUcConverter::getFormatBufferLength(len);
char* buffer = new char[buflen]; // Here is the memory leak marked by Fortify
if(valueCanBeLogged) {
LOGMSG(_DBUG, "nameForLog=%s, len=%d, sapuc='%.*s'",
nameForLog, len, buflen,
SapUcConverter::format(buffer, sapuc, len));
} else {
LOGMSG(_DBUG, "nameForLog=%s, len=#####, sapuc=#####");
}
delete[] buffer;
如果SapUcConverter::format
或任何在LOGMSG
展开时可能调用的函数(假设是宏)不声明noexcept
, then as far as the code that calls them knows, they may throw. And if they do, then buffer
leaks. Solution: Adhere to RAII原则。 RAII 的最简单方法是使用 std::vector
或 std::string
.
SapUcConverter::format() is a long function for building a logging string. There is no throw in it.
仅仅因为没有 throw
表达式,并不意味着它不能抛出。听起来它可能会分配动态内存。 new
表达式可以抛出。附加到 std::string
可能会抛出。但是,如果您 100% 认为 SapUcConverter::format
中的任何表达式都不会抛出,那么您可以使用 noexcept 说明符。