我总是删除数组delete[].但HP Fortify显示出内存泄漏.我的代码出了什么问题?
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;
Run Code Online (Sandbox Code Playgroud)
如果SapUcConverter::format或者在LOGMSG扩展时可能被调用的任何函数(假设它是一个宏)没有被声明noexcept,那么只要调用它们的代码知道,它们就可以抛出.如果他们这样做,那么buffer泄漏.解决方案:坚持RAII原则.RAII的最简单方法是使用std::vector或std::string.
SapUcConverter :: format()是一个用于构建日志字符串的长函数.它没有投掷.
只是因为没有throw表达,并不意味着它不能抛出.听起来它可能会分配动态内存.new表达式可以抛出.附加std::string可能会抛出.但是如果你是100%没有表达式SapUcConverter::format可以抛出,那么你可以使用noexcept说明符.