2016-10-02 110 views
5

我写这样的代码:ptr = free(ptr),NULL安全吗?

#include <stdlib.h> 

int main(void) 
{ 
    void *kilobyte; 
    kilobyte = malloc(1024); 
    kilobyte = NULL, free(kilobyte); 
    return 0; 
} 

的对称性,这是很好的。但我从来没有见过任何人使用之前这个成语,所以,我不知道这实际上可能是不可移植/不安全的,尽管这Wikipedia报价:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).


编辑:混合起来的顺序。现在它编译在gcc没有任何警告。

+0

'free'没有返回值,所以该行不良作风。代码甚至没有更少的输入,使用标准的代码。 – Olaf

+0

AFAIK,逗号运算符丢弃'free'值,这是'void',并使用'NULL'代替。如果你的风格需求在释放它们之后始终将指针指向NULL,那么它**少输入。 –

+0

丢弃没有价值!你有没有试图在问之前编译这个?你有没有在标准中找到合法或非法的证据?请引用该部分。 (哦,我用gcc尝试过)。 – Olaf

回答

11

通过这样做:

kilobyte = NULL, free(kilobyte); 

您有内存泄漏。

您设置kilobyte为NULL,所以不管它的内存被指向不再在任何地方引用。然后当你做free(kilobyte)时,你实际上在做free(NULL),它不执行任何操作。

关于free(NULL),从C standard

7.22.3.3 The free function

1.

#include <stdlib.h> 
void free(void *ptr); 

2. The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc , the behavior is undefined.

至于编辑之前,你的原始代码:

kilobyte = free(kilobyte), NULL; 

这样做的问题是,=操作符比,运营商更高的优先级,所以这个说法实际上是:

(kilobyte = free(kilobyte)), NULL; 

这试图设置这是不允许到void的变量。

什么你可能缩进做的是:

kilobyte = (free(kilobyte), NULL); 

这释放的指针,然后将指针设置为NULL。

正如意见中提到的奥拉夫,而不是一条线做的一切,但最好要做到这一点,而不是:

free(kilobyte); 
kilobyte = NULL; 

这样做,这是比冷凝代码为更清楚地向读者其他人可能不了解,并且(如您现在所见)不太容易出错。

相关问题