Pointer Quiz Ques no 4

why is there memory leak in this code snippet?
int main()
{
int *ptr = (int *)malloc(sizeof(int));
ptr = NULL;
free(ptr);
}

Hey Kiran, here ptr is pointing to some memory which is not freed and ptr pointer is assigned to NULL, So it will results in a memory leak. To avoid this memory leak correct sequence of code should be

int main()
{
     int *ptr = (int *)malloc(sizeof(int));
     free(ptr);
     ptr = NULL;
}

Here first we free the memory to which ptr is pointing and then assigning NULL to ptr.