Please see the following code:
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> void destroy(int * p){ if(p != NULL) { free(p); p = NULL; } } int main() { int *p; p = (int*)malloc(sizeof(int)*5); p[0] = 1; p[1] = 2; destroy(&p); if(p == NULL) printf("AAAAAAAA\n"); else printf("BBBBBBB\n"); return 0; }
Compile execution, output:
The P in the
BBBBBBB
function is a temporary variable that is passed into P. The pointing space is indeed free, but the assignment NULL is assigned to temporary variables.
Modify the Destroy function as follows, solve this problem.
void destroy(int ** p){ if(*p != NULL) { free(*p); *p = NULL; } }
Compile running output:
AAAAAA
Reprinted: https://www.cnblogs.com/biglucky/p/4651196.html