ProgrammingHard

Which loop correctly frees every node of a singly linked list whose head is p?

  1. A. while (p) { free(p); p = p->next; }
  2. B. while (p) { q = p->next; free(p); p = q; }
  3. C. for (q = p; q; q = q->next) free(q);
  4. D. while (p->next) { free(p); p = p->next; }

Correct answer: B. while (p) { q = p->next; free(p); p = q; }

The next pointer is saved before the node is freed. The other loops read memory after it has been freed, or skip the last node.

More C Programming questions

Exams that ask this topic