简体   繁体   English

双指针作为函数参数

[英]Double pointer as function parameter

I was reading a page of "Understanding and Using C Pointers" when this function appeared: 此功能出现时,我正在阅读“理解和使用C指针”页面:

void safeFree(void **pp) {
  if (pp != NULL && *pp!= NULL) {
    free(*pp);
    *pp = NULL;
  }
}

and an example code from it: 以及其中的示例代码:

int main(int argc, char **argv) {
  int* pi = (int*)malloc(sizeof(int));
  *pi = 5;
  safeFree((void**)&pi);

  return EXIT_SUCCESS;
} 

My point is, checking pp != NULL in the if condition in this scenario is useless, right? 我的意思是,在这种情况下,在if条件下检查pp != NULL是对的吗? Because according to the way this code is written this condition will never be false. 因为根据编写此代码的方式,此条件永远不会为假。 But there is a scenario in which this condition will be true, assuming **pp expects a memory address and (assumed by me) a memory address of a variable can never be NULL ? 但是在这种情况下,如果**pp期望一个内存地址并且(假设我)一个变量的内存地址永远不能为NULL ,那么这种情况将为真? Or did the writer did that checkup in case someone did something like this? 还是作者做了检查,以防有人做了这样的事情?

int main(int argc, char **argv) {
  int **pi = NULL;
  safeFree((void**)pi);

  return EXIT_SUCCESS;
}

Thanks. 谢谢。

The function checks for NULL mainly for cases like your second. 该函数主要在第二种情况下检查NULL。 If an actual variable address is passed that check will not fail but never trust your caller to be sane. 如果通过了实际的变量地址,该检查将不会失败,但永远不要相信您的调用方是理智的。

Having said that safeFree is just confusing and does not provide safety. 说了这么多safeFree只是混乱, 提供安全性。 Because the code assumes that the API user will always pass a particularly constructed pointer. 因为代码假定API用户将始终传递特别构造的指针。 Consider these: 考虑这些:

tricky 0 (screws up a) 棘手的0(拧紧一个)

#include <stdio.h>
#include <stdlib.h>


void safeFree(void **pp) {
  if (pp != NULL && *pp!= NULL) {
      free(*pp);
      *pp = NULL;
  }
}

int main() {
    int *a;
    int **p;
    a = malloc(5 * sizeof(int));
    p = malloc(1 * sizeof(a));
    a[0] = 10;
    p[0] = a;
    fprintf(stderr, "%d\n", a[0]);
    safeFree((void **)p); /* grrrr */
    fprintf(stderr, "%d\n", a[0]);
}

tricky 1 (crashes) 棘手的1(崩溃)

int main() {
    int a[] = { };
    int b[] = { 1 };
    int c[] = { 2 };

    int **p = malloc(3 * sizeof(int *));
    p[0] = a, p[1] = b, p[2] = c;

    safeFree((void **)p); /* grrrr */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM