c - 为什么在这个例子中使用 q?

标签 c

"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 whether malloc() is called; if not, q remains set to NULL. Passing NULL to free() is guaranteed to safely do nothing.

因此,q 的目的是让您的代码确定是否调用了 malloc()

如果p为非NULL,则malloc()不被调用,q。如果 pNULL,则调用 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/

相关文章:

c - 我无法纠正此 C 代码中的错误,该代码接受用户输入以使用 scanf 填充二维数组

c - C 中分割数字的总和

无法在 OpenBSD 上使用 editline 进行编译

c - Lapack 在尝试反转矩阵之前是否检查矩阵是否可逆

c - 读取字符串并在结构中存储为 int 的最安全方法

c++ - 如何在 MATLAB 中编写 max(abs)

c++ - 具有嵌套结构的动态数组

c - 链接实际上是如何在内部发生的?

c - Sscanf 带有数据的字符串

c - 使用套接字编程时何时使用bind()?