Pointers mcq in the algo c ++ q4

the pointers mcq has this question where it asks what the error is and then gives this code
int main()
{
int *ptr = (int *)malloc(sizeof(int));
ptr = NULL;
free(ptr);
}

and the answer shows that the error is memory leak but ptr is freed over here, in fact there is no return statement so shouldn’t that be the error. either way please clarify. Thank you !

@amishalucyrath
After the execution of the first statement ,
int *ptr = (int *)malloc(sizeof(int));
ptr has been allocated a box of memory in the heap memory. Only ptr knows the address to this location,
In the next statement , we reassign the value in ptr
ptr = NULL;
ptr now points to no location as it as NULL in it. The box of memory that was allocated to it is still there however it has no pointer pointing to it. Noone knows its location now.
Now even though we used the statement ,
free(ptr);
this only works on the location ptr is pointing to now , which happens to be NULL. Hence the box that was allocated remains and not deleted . This is a case of memory leak.

1 Like

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.

1 Like