Multiple choice

struct node nPtr, *sPtr; / pointers for a linked list. */ for (nPtr=sPtr; nPtr; nPtr=nPtr->next) { free(nPtr); } The sample code above releases memory from a linked list. Which of the choices below accurately describes how it will work?

  1. It will work correctly since the for loop covers the entire list.

  2. It may fail since each node nPtr is freed before its next address can be accessed.

  3. In the for loop, the assignment nPtr=nPtr->next should be changed to nPtr=nPtr.next.

  4. This is invalid syntax for freeing memory.

  5. The loop will never end.

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The code frees nPtr before accessing nPtr->next, creating a use-after-free bug. Once free() is called, accessing nPtr->next is undefined behavior. The correct approach is to save nPtr->next before freeing nPtr.