edited by
1,100 views
0 votes
0 votes

Consider the C node fragment given below:

Which of the following true about above code if input is given as linked list of n-element in which for each node memory is created in heap area?

A. Compiles successfully but execution may result in dangling pointer.

B. Compiles successfully but execution may result in memory leak problem.

C. It will produce compile time error.

D. Compilation error because p = = NULL not present after free (p) in else part.


I think answer should be C. Because the return type is int node* 

Can someone please confirm.

edited by

1 Answer

0 votes
0 votes

No one seems to have noticed this sneaky line here -:

else if(s->next = NULL)

Here it should be $==$ and not $=$. So $s->next$ will get assigned $NULL$ each time this statement is executed. If you studied C/C++ in school, you'll probably vaguely remember your teacher warning you to not write $if(x = 5)$.

Think of a long linked list, and you provide the head pointer of that list to this function. What this code will do is set the first node's next pointer to $NULL$, free the memory occupied by the first node and then set the head pointer $s$ to $NULL$. Which is fine, but now the rest of the linked list is inaccessible and the memory can't be freed.

So the answer is $B$.

Related questions

3 votes
3 votes
2 answers
3
Shamim Ahmed asked Dec 11, 2018
547 views
char *a = “MADEEASY”;char *b = “GATECSIT2019”;char *r = a;char *s = b;printf(“%d”, (int) strlen (b+3[r] – 1[s]));return 0; Whats the output? Answer given 8
0 votes
0 votes
0 answers
4