The Gateway to Computer Science Excellence
+1 vote

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.

in Programming by
edited by | 265 views
yes, dangling pointer and memory leak both not issue here

So, C most relevant

It will give Runtime error of type SEGFAULT when the list is empty, and also on the error you point out.

@srestha I think it is currently not in Memory leak, but if we interchange the below two lines in the above code then it will definitely cause Memory leak.

s = NULL


memory leak of one node.

Don't we need p=NULL in the last part?

1 Answer

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

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
52,315 questions
60,428 answers
95,238 users