Multiple choice

struct node nptr,*sptr; /*pointers for linked list/ for(nptr=sptr;nptr;nptr=nptr->next) { free(nptr); }

Releases memory from a linked list. Which of the following 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. This is invalid syntax for freeing memory.

  4. The loop will never end.

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

The loop frees nptr BEFORE reading nptr->next in the next iteration. After free(nptr), accessing nptr->next is undefined behavior - the memory has been deallocated. The correct approach is to save nptr->next BEFORE freeing nptr: next = nptr->next; free(nptr); nptr = next;