Consider the C code fragment given below. typedef struct node { int data;…

2017

Consider the C code fragment given below.

typedef struct node {
int data;
node* next;
} node;
void join(node* m, node* n) {
node* p = n;
while(p->next != NULL) {
p = p->next;
}
p->next = m;
}
Assuming that m and n point to valid NULL-terminated linked lists, invocation of join will

  1. A.

    append list m to the end of list n for all inputs.

  2. B.

    either cause a null pointer dereference or append list m to the end of list n.

  3. C.

    cause a null pointer dereference for all inputs.

  4. D.

    append list n to the end of list m for all inputs.

Attempted by 317 students.

Show answer & explanation

Correct answer: B

Answer: The function will either cause a null pointer dereference (if n is NULL) or append list m to the end of list n (otherwise).

Explanation:

  • p is initialized to n. If n is NULL, then p is NULL and the attempt to read p->next dereferences a null pointer, causing undefined behavior (likely a crash).

  • If n is non-NULL, the while loop advances p until p points to the last node of n (the node whose next is NULL).

  • The assignment p->next = m links the head of list m after the last node of n, so m is appended to n. If m is NULL, this assignment simply leaves the list terminated (no effective change).

  • Therefore the function has two possible behaviors depending on the value of n: it crashes if n is NULL, otherwise it appends m to the end of n.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir