在 "Compliant Solution" code example 中, 变量 q
被使用。
但是,我不确定为什么要在这种情况下使用 q
。
char *p = /* Initialize; may or may not be NULL */
char *q = NULL;
if (p == NULL) {
q = (char *) malloc(BUF_SIZE);
p = q;
}
if (p == NULL) {
/* Handle malloc() error */
return;
}
/* Perform some computation based on p */
free(q);
q = NULL;
相反,以下代码的行为是否与上述代码相同?
char *p = /* Initialize; may or may not be NULL */
if (p == NULL) {
p = (char *) malloc(BUF_SIZE);
}
if (p == NULL) {
/* Handle malloc() error */
return;
}
/* Perform some computation based on p */
最佳答案
如果您点击您提供的链接,您可以阅读这段文字:
In this compliant solution, a second pointer,
q
, is used to indicate whethermalloc()
is called; if not,q
remains set toNULL
. PassingNULL
tofree()
is guaranteed to safely do nothing.
因此,q
的目的是让您的代码确定是否调用了 malloc()
。
如果p
为非NULL
,则malloc()
不被调用,q
为空
。如果 p
为 NULL
,则调用 malloc()
,并且 q
为非 NULL
.
我个人认为这是一个奇怪的例子,几乎被混淆了。与简单的代码相比,这可能带来的任何轻微的性能提升都是不值得的。
我会写:
#include <stdbool.h>
char *p = /* Initialize; may or may not be NULL */
bool malloc_was_called = false;
if (p == NULL) {
p = (char *) malloc(BUF_SIZE);
malloc_was_called = true;
}
if (p == NULL) {
/* Handle malloc() error */
return;
}
/* Perform some computation based on p */
if (malloc_was_called) {
free(p);
p = NULL;
}
编辑:我不是很清楚,但是使用q
的目的是释放内存但前提是函数分配了它。如果 p
指向某物,我们不会释放它;但是如果我们分配了内存,我们就会释放它。以前这很棘手,但我的重写使恕我直言更加清晰。
关于c - 为什么在这个例子中使用 q?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23749000/