避免使用
malloc()和free(),而是首选具有nothrow的new的delete版本 (r.10)
此警告根据 R.10(避免使用 malloc 和 free)标记了显式调用 malloc 或 free 的位置。 解决此类警告的一种可能的方法是使用 std::make_unique,以避免显式创建和销毁对象。 如果不能接受此类解决方法,应首选 new and delete 运算符。 在某些情况下,如果不接受异常,可以将 malloc 和 free 替换为 new 和 delete 运算符的 nothrow 版本。
备注
为了检测
malloc(),我们会检查调用是否激活名为malloc或std::malloc的全局函数。 此函数必须返回一个指向void的指针且接受一个无符号整型类型的参数。若要检测
free(),可以检查名为free或std::free的全局函数,这些函数不返回任何结果且接受一个参数,该参数是指向void的指针。
代码分析名称:NO_MALLOC_FREE
另请参阅
示例
#include <new>
struct myStruct {};
void function_malloc_free() {
myStruct* ms = static_cast<myStruct*>(malloc(sizeof(myStruct))); // C26408
free(ms); // C26408
}
void function_nothrow_new_delete() {
myStruct* ms = new(std::nothrow) myStruct;
operator delete (ms, std::nothrow);
}