MCQ pointers--Memory Leak Ques 4

Q­4 What is the problem with the following code #include<stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
ptr = NULL;
free(ptr);
}

when its written free then how memory leak??

There is no problem with the code. What is your query? Please elaborate.

Memory leak refers to illegal access of memory because of the presence of pointers. With the help of pointer, the user can make changes with the memory which may not be allowed.

1 Like

@sss when its written free then that means pointer if free so no memory leak should be there right.Please correct me if i’m wrong.

Hey Vushnupriya, the problem is memory leak beacuse p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be

free ( p );
p = NULL;

yeah i got that …thanks but do we need to point the pointer to null after writing free(ptr)…please explain this also.

Yes, because free(ptr) this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. So, we should point ptr to NULL after that.

free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

this is written on geeksforgeeks-- https://www.geeksforgeeks.org/g-fact-30/

If ptr is null, the free() function does nothing.
If ptr does not point to a memory block allocated by calloc, malloc or realloc functions, it causes undefined behavior.

this too i found - https://www.programiz.com/cpp-programming/library-function/cstdlib/free

Now i am totally confused ;(