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 and point to valid NULL-terminated linked lists, invocation of join will
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 .
Consider the function:
void join(node* m, node* n) {
node* p = n;
while (p->next != NULL) {
p = p->next;
}
p->next = m;
}
Case 1: is an empty list (). 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: is a non-empty list (). The pointer p advances until p->next == NULL, which is the last node of list . Then p->next = m; sets the next pointer of the last node of to point to the head of list . This successfully appends list to the end of list .
Therefore, invocation of join will either cause a null pointer dereference (when is NULL) or append list to the end of list (when is non-empty).
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.