【发布时间】:2014-09-04 12:00:47
【问题描述】:
这两种方法都有效,但在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;
}
}
如果我离开该方法,是否需要if 查询?无论如何,给free 内存不是一样快吗?
void baa()
{
str *ptr = NULL;
// try to malloc memory and do something
// leaving methode and free the memory
free(ptr);
ptr = NULL;
}
【问题讨论】:
-
free (ptr)你的意思是,对吧? -
你为什么要标记 C++?在 C++ 中通常不会使用
malloc/free,而且在大多数情况下,您也不会使用动态分配。 -
最后的
ptr = NULL也是没有意义的(尽管编译器应该意识到这一点并且不会为它生成任何浪费时间的代码)。 -
我修改了问题:将
prt换成ptr。如果这是故意的,请回滚。 -
@crashmstr:当然,在新代码中。我在旧代码和成长代码中遇到了这个问题。 (超过 100.000 行代码)。我不能把所有东西都写新!
标签: c++ c pointers malloc free