MCQ Pointers Question

What is the problem with the following code #include<stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
ptr = NULL;
free(ptr);
}
A) Dangling Pointer
B) Memory leak
C) The program may crash as free() is called for NULL pointer.
D) Compiler Error

how option b is correct

@sandeep021 free() can be called for NULL pointer, so no problem with free function call.

The problem is memory leak because p is allocated some memory which is not freed because the pointer is assigned as NULL. The correct sequence should be

free ( p );
p = NULL;

So correct answer is B

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.