MCQ - Pointers doubt

please explain the solution of 4th mcq in pointer

Hi @Shreya-Gupta-2383169445069382, in question 4 the problem arises with line

int *ptr = (int *)malloc(sizeof(int));

Here what is happening is we created a pointer ptr of type int.
And then we say that ptr sould point to an int type data by means of:

(int *)malloc(sizeof(int))
We have already said/decleared that ptr will be an int type pointer but then also *(int )… is written. Here, memory is getting wasted. And thus it is memory leak. 4 bytes of memory is wasted here as we allocated a new place to ptr without properly deallocating it’s previous location.

Hope this helps :slight_smile:

4 bytes of memory is wasted here as we allocated a new place to ptr without properly deallocating it’s previous location. i dont understand this line

@Shreya-Gupta-2383169445069382
We allocated a location dynamically to ptr.
In the next line we assign NULL to ptr.

So the earlier location that we assigned to ptr is still allocated in program but nothing points to it anymore. So we should deallocate that space before assigning NULL to ptr.

If your doubt is resolved please mark it as closed.