Possible Duplicate:
Setting variable to NULL after free …
I am learning about good C programming practices and my friend told me to always set the pointers to NULL after free()ing them (or calling a specific freeing function).
For example:
char* ptr = malloc(100);
...
free(ptr);
ptr = NULL;
or
struct graph* graph = create_graph();
...
destroy_graph(graph);
graph = NULL;
Why is this a good practice?
Update: After reading the answers, it seems an awful practice to me! I am hiding possible double-free() errors. How can this possibly be a good practice? I am shocked.
Thanks, Boda Cydo.
Bad practice vote from me. If you do want to assign a value, set it to (void*)0xdeadbeef. Check what your CRT can do first though. A decent debug allocator will set freed memory to a pattern that’s likely to cause a bomb when the pointer is used after it was freed. Albeit that it isn’t guaranteed. But then not changing the pointer value is the better (and faster) solution.