Question

Consider the C code fragment given below.

typedef struct node {
    int data;
    struct node* next;
} node;

void join(node* m, node* n) {
    node* p = n;
    while (p->next != NULL) {
        p = p->next;
    }
    p->next = m;
}

Assuming that mm and nn point to valid NULL-terminated linked lists, invocation of join will

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2017 answer key

Solution

Trace the behavior of join(m, n) under both empty and non-empty list inputs for nn.

Consider the function:

void join(node* m, node* n) {
    node* p = n;
    while (p->next != NULL) {
        p = p->next;
    }
    p->next = m;
}

Case 1: nn is an empty list (n==NULLn == \text{NULL}). Then p = n becomes p = NULL. When the while condition checks p->next != NULL, it attempts to dereference a NULL pointer (NULL->next), resulting in a runtime null pointer dereference error (segmentation fault).

Case 2: nn is a non-empty list (n≠NULLn \ne \text{NULL}). The pointer p advances until p->next == NULL, which is the last node of list nn. Then p->next = m; sets the next pointer of the last node of nn to point to the head of list mm. This successfully appends list mm to the end of list nn.

Therefore, invocation of join will either cause a null pointer dereference (when nn is NULL) or append list mm to the end of list nn (when nn is non-empty).

Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 1
Question
8 of 65, printed as CS Q.8
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.