In this code, relied on gdb, p changes from 0x602010 to 0x0 when NULL is assigned, (as I would expect)
#include<stdio.h> #include<stdlib.h> int main() { int a = 10; // gdb output int *p = (int *) malloc(sizeof(int)); // p = (int *) 0x602010 p = NULL; // p = (int *) 0x0 p = &a; // p = p = (int *) 0x7fffffffe15c return 0; } But, when p is changed outside of main() in task(), I guess it does not change to 0x0 and I don't why:
#include<stdio.h> #include<stdlib.h> void tast(int *p); void task(int *p) { /* before (gdb) p p $1 = (int *) 0x7fffffffe15c (same as variable a) (gdb) p &p $2 = (int **) 0x7fffffffe128 */ p = NULL; /* after (gdb) p p $3 = (int *) 0x7fffffffe15c no change? (gdb) p &p $4 = (int **) 0x7fffffffe128 */ } int main() { int a = 10; // gdb output int *p = (int *) malloc(sizeof(int)); // p = (int *) 0x602010 p = NULL; // p = (int *) 0x0 p = &a; // p = p = (int *) 0x7fffffffe15c // it is possible to change what p points to // after calling task()? task(p); // p will be NULL? return 0; } Why p does not change to 0x0 inside task()?
intintaskwould you expect the change to propagate? You'll need to pass a pointer to a pointer if that's the behavior you want.pis not changed inside task() the compiler may have optimized away any changes to the value.