C Programming Basics
In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?
- AUnless NULL is assigned, the released region does not become available again, causing a memory leak
- Bp keeps pointing to the released region, so this prevents double frees and use after free and makes them easier to find
- Cfree sets p to NULL automatically, but writing the same value again is a safety check
Show answer and explanation
Answer: B. p keeps pointing to the released region, so this prevents double frees and use after free and makes them easier to find
free(p) releases the region p pointed to, but the value (address) of the variable p remains unchanged. Reading or writing *p afterwards is use after free, and calling free(p) again is a double free; both are undefined behavior and can corrupt the heap's bookkeeping so that a failure appears somewhere far away. If p is set to NULL, the double free is harmless because free(NULL) is defined to do nothing, and a NULL check before use also reveals the mistake. Other pointer variables that point to the same region still need separate care.
- A. The region is released when free is called. Assigning NULL has nothing to do with whether it is released.
- B. Correct. It prevents use after free and double frees and makes them easier to find.
- C. free does not change the value of p. After the call, p still points to the released address.