pos*_*irk 1 c c++ malloc free pointers
这两种方法都有效,但哪一种方法更快/更高效ptr == NULL?
void voo()
{
str *ptr = NULL;
// try to malloc memory and do something
// leaving methode and free the memory
if(ptr != NULL)
{
free(ptr);
ptr = NULL;
}
}
Run Code Online (Sandbox Code Playgroud)
if如果我离开方法,我是否需要查询?free在任何情况下都不能快速提供内存吗?
void baa()
{
str *ptr = NULL;
// try to malloc memory and do something
// leaving methode and free the memory
free(ptr);
ptr = NULL;
}
Run Code Online (Sandbox Code Playgroud)
从C标准,7.20.3.2/2,如果ptr是NULL则free(ptr)什么都不做.
因此,从性能和多余的代码角度来看,检查这一点毫无意义.