I'm working with search trees, and to see if the tree ended I check if it's null. My problem is when I use free() the pointer value doesn't become NULL.
I've also tried using a pointer to free and then set to NULL but it didn't work.
In this case I want to remove the biggest number on a search tree but my print function doesn't recognize the freed value and prints 0 instead.
typedef struct nodo {
int val;
struct nodo *l, *r;
} *ABin;
void print (ABin a) {
if (a != NULL) {
print (a -> l);
printf(" %d ",a -> val);
print (a -> r);
}
}
ABin remBiggerA (ABin *a) {
ABin b = (*a), aux = b;
int i = 0;
if (b == NULL) i = 1;
while (i == 0) {
if (b -> r == NULL) {
free (b);
i = 1;
}
else b = b -> r;
}
(*a) = aux;
return aux;
}
After calling free()
on a pointer, it doesn't set the pointer to null, it invalidates it. This means that further access to that pointer address results in undefined behaviour. You simply can't access or print information from memory that has already been freed. You can, however, free a pointer and then immediately set it to null yourself - that is a perfectly valid thing to do. If you do this already and still have issues, then I suspect your problem lies somewhere else.