+1 vote
265 views

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 | 265 views
+1
yes, dangling pointer and memory leak both not issue here

So, C most relevant
0

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

free(s);

memory leak of one node.

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

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$.

by