简体   繁体   中英

Double pointer as function parameter

I was reading a page of "Understanding and Using C Pointers" when this function appeared:

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? 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 ? 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. 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. Because the code assumes that the API user will always pass a particularly constructed pointer. Consider these:

tricky 0 (screws up a)

#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)

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 */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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