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
View worked solution
Answer: B
Let us analyze the behavior of the function join(node* m, node* n) based on the input list n:
-
Case 1: The list
nis empty (i.e.,n == NULL)A
NULLpointer is a valid representation of an empty NULL-terminated linked list. IfnisNULL, then:node* p = n; // p becomes NULLWhen the loop condition
while(p->next != NULL)is evaluated, it attempts to dereferencep->next(which isNULL->next). This results in a null pointer dereference (runtime error/segmentation fault). -
Case 2: The list
nis non-empty (i.e.,n != NULL)The
whileloop traverses the listnuntilppoints to the last node (wherep->next == NULL). After exiting the loop, the statement:p->next = m;links the last node of list
nto the head of listm, effectively appending listmto the end of listn.
Thus, the invocation of join will either cause a null pointer dereference (when n is empty) or append list m to the end of list n (when n is non-empty).
Therefore, the correct option is B.
Free practice · Your answers on this page are not saved.
