Consider the following program:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int value;
struct Node *next;};
int main( ) {
struct Node *boxE, *head, *boxN; int index=0;
boxE=head= (struct Node *) malloc(sizeof(struct Node));
head → value = index;
for (index =1; index<=3; index++){
boxN = (struct Node *) malloc (sizeof(struct Node));
boxE → next = boxN;
boxN → value = index;
boxE = boxN; }
for (index=0; index<=3; index++) {
printf(“Value at index %d is %d\n”, index, head → value);
head = head → next;
printf(“Value at index %d is %d\n”, index+1, head → value); } }
Which one of the following statements below is correct about the program?
View worked solution
Answer: D
Let's trace the execution of the program step-by-step:
1. Linked List Creation:
- Initially, a node is allocated and pointed to by
headandboxE. Its value is set to0. - The
forloop runs forindex = 1, 2, 3, allocating three more nodes (with values1,2, and3) and linking them. - At the end of this loop, the last node (value
3) is pointed to byboxE. However,boxE->nextis never initialized toNULL. Since memory is allocated viamalloc,boxE->nextcontains garbage/uninitialized data.
2. Printing Loop:
The second loop runs for index = 0, 1, 2, 3:
- For
index = 0, 1, 2, the program successfully prints the values of the nodes (0, 1, 2, 3) asheadadvances from Node 0 to Node 3. - For
index = 3:- The first
printfprints the value of Node 3 (which is3). - The statement
head = head->next;assigns the uninitializednextpointer of Node 3 tohead. - The second
printfattempts to dereference this uninitialized pointer viahead->value.
- The first
Dereferencing an uninitialized pointer leads to undefined behavior and typically results in a segmentation fault (run-time error).
Free practice · Your answers on this page are not saved.
