Open In App
Related Articles

C | Dynamic Memory Allocation | Question 7

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
What is the problem with following code?
#include<stdio.h>
int main()
{
    int *p = (int *)malloc(sizeof(int));
  
    p = NULL;
  
    free(p);
}

                    
(A) Compiler Error: free can’t be applied on NULL pointer (B) Memory Leak (C) Dangling Pointer (D) The program may crash as free() is called for NULL pointer.

Answer: (B)

Explanation: free() can be called for NULL pointer, so no problem with free function call. The problem is memory leak, p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be following:
    free(p);
    p = NULL;


Quiz of this Question

Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads