free pointer to pointer
-
-
Hello, there's a code.
#include #include #include int main()
{
char* x = (char*)calloc(sizeof(char),150);
char* p = x;
free(x);
x = NULL;
.....
//p = NULL (get from x)
return 0;
}Tell me how to get NULL under p when x is removed and set to NULL.
You have to set it explicitly, there is no garbage collector or reference counts in C. The two pointers have no connection, so when you free
x
, pointerp
still points to the original block of memory. You must be very careful to manage dynamic memory properly in C, and even in C++. -
Hello, there's a code.
#include #include #include int main()
{
char* x = (char*)calloc(sizeof(char),150);
char* p = x;
free(x);
x = NULL;
.....
//p = NULL (get from x)
return 0;
}Tell me how to get NULL under p when x is removed and set to NULL.
You have not a pointer to pointer. As Richard correctly pointed out, you have two independent pointers to the same block of memory; you have to explicitely set
p = NULL;
. With a pointer to pointer the scenario would change:char* x = (char*)calloc(sizeof(char),150);
char** p = &x;
free(x);
x = NULL;
printf("%p\n", *p); // here *p is NULL -
You have not a pointer to pointer. As Richard correctly pointed out, you have two independent pointers to the same block of memory; you have to explicitely set
p = NULL;
. With a pointer to pointer the scenario would change:char* x = (char*)calloc(sizeof(char),150);
char** p = &x;
free(x);
x = NULL;
printf("%p\n", *p); // here *p is NULL -