免费(指针)方法的性能?

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)

Bat*_*eba 9

从C标准,7.20.3.2/2,如果ptrNULLfree(ptr)什么都不做.

因此,从性能和多余的代码角度来看,检查这一点毫无意义.

  • +1.在它超出范围之前将`ptr`设置为'NULL`也是没有意义的,嘈杂和混乱. (4认同)
  • 只是为了明确:通常,在free'ing之后将指针设置为NULL是好的.这里没有意义,只是因为`ptr`的范围有限. (2认同)