3.
Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Avoiding dangling pointers**
Which of these code snippet given in the choices helps avoid dangling pointer in C?
**
Show answer & explanation
Answer: A. A) ```c
Assigning NULL to the pointer immediately after calling free(ptr) ensures it no longer references deallocated memory, preventing dangling pointer vulnerabilities.
Step-by-step Derivation:
Step 1: free(ptr) releases the allocated memory block on the heap, but ptr still holds the deallocated address (dangling pointer).
Step 2: Subsequent dereference of a dangling pointer causes undefined behavior.
Step 3: Setting ptr = NULL immediately after free(ptr) neutralizes the pointer, preventing dangling references.