ProgrammingHard
Which loop correctly frees every node of a singly linked list whose head is p?
- A. while (p) { free(p); p = p->next; }
- B. while (p) { q = p->next; free(p); p = q; }
- C. for (q = p; q; q = q->next) free(q);
- 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
- A recursive function prints a list after its recursive call returns, as in print(n) { if (!n) return; print(n->next); putchar(n->v + '0')…
- In a 6-node list with values 10, 20, 30, 40, 50, 60, the standard slow and fast pointer method (slow moves one step, fast two steps, while…
- Which operation removes the k-th node (1-based) from a singly linked list in one pass with a pointer to the previous node, and handles…
- Which realloc pattern does not leak memory or lose the original block if the reallocation fails?
- A dynamic array doubles its capacity whenever it is full. Pushing N = 10^6 values costs about how many element copies in total?
- A function returns a pointer to a node created with malloc inside it. Which description is correct?