408 views

Consider the following program. printlist() is a function that takes the head of a linked list and prints all nodes values separated by comma. Node is typedefed singly linked list type struct.

void insert1(Node *head,int data)
{
Node *NewNode= (Node *)malloc(sizeof(Node));
NewNode->value=data;
}
{
Node *NewNode= (Node *)malloc(sizeof(Node));
NewNode->value=data;
}
int main()
{
/* create a linked list 1->2->3->4->5
and head points to the first node.*/

//The list is restored to its initial state

}


Which of the following is/are true about the above program?

1. Line $\text{X}$ prints $9,1,2,3,4,5$
2. Line $\text{Y}$ prints $9,1,2,3,4,5$
3. Line $\text{X}$ prints $1,2,3,4,5$
4. Line $\text{Y}$ prints $1,2,3,4,5$

@GO Classes @Mittal sachin Sir had the printList function been called within insert1(), after the 4 line. It should have printed the 9 1 2 3 4 5? Is it not sir?

2. {
3. Node *NewNode= (Node *)malloc(sizeof(Node));
4. NewNode->value=data;
7. printList(head); // it should print 9 1 2 3 4 5
8. }

Because of 2 concepts :

1.) CALL BY VALUE :

2.) CALL BY REFERENCE :

X: After insert1() memory is in heap: with no reference to given to outside world, hence “MEMORY LEAK”

Y: Same as that of X but in this case reference of head changes, the head act as a pointer to memory created inside function even after it(function) gets destroyed.

Answers are option B and option C 