How to avoid dangling pointers?

To get rid of dangling pointers, after freeing the pointer, can we assign NULL. Is this be an acceptable solution. Since

free(NULL)

won't do any operation.

main(){
 void *ptr = malloc(10);
 free(ptr); 
 ptr = NULL;
 free(ptr);
}

The second call to free() has no effect, stop after the assignment of NULL to the pointer.

To avoid free-ing dangling pointers: "Don't do that". If you're finding your programs in situations where it's even trying to free dangling pointers, that's a big problem you should solve instead of just mitigating. Fix the problem.

Basically, you want it to crash when you do that. You want it to crash right now, when the problem is still on the stack, not when it's too late to find out what crashed it. There are some really badly-coded heaps out there, i.e. Microsoft, which will happily swallow bad data and crash far later under untraceable circumstances.