Multiple choice technology programming languages

void Free( struct node *ptr ) { while( ptr) { ???? } } Which one of the following can replace the ???? for the function above to release the memory allocated to a linked list?

  1. n = n->next; free( n );

  2. struct node m = n; n = n->next; free( m );

  3. free( n ); n = n->next;

  4. struct node m = n; free( m ); n = n->next;

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

To free a linked list, you must save the next pointer BEFORE freeing the current node, then advance. Option B: 'struct node m = n; n = n->next; free(m);' correctly copies the pointer, advances n to next, then frees the original node. Option A frees next instead of current (memory leak), Option C frees before reading next (use-after-free crash), Option D frees before advancing (memory leak).