When does a dangling pointer occur?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
When does a dangling pointer occur?
Show answer & explanation
A dangling pointer occurs when a pointer continues to reference memory that has been deallocated or is no longer valid. This happens when a dynamic memory block is freed but the pointer variable is not set to null, or when a pointer references a local variable that goes out of scope. Option B describes an uninitialized pointer (not dangling), Option A is incorrect because static local variables persist for the program lifetime, and Option D incompletely describes the problem—it's not the act of freeing that creates the dangling pointer, but the pointer's continued use afterward.
Step-by-step Derivation:
Key scenarios for dangling pointers:
- Use-after-free: int *p = new int(5); delete p; *p = 10; // p is now dangling
- Returning address of local variable: int* func() { int x = 5; return &x; } // dangling after function returns
- Pointer to freed stack memory: Accessing a pointer after its referent goes out of scope
Uninitialized pointers (B) point to random addresses but are not inherently "dangling" in the technical sense. A dangling pointer specifically points to memory that was once valid but is now invalid.