What is the problem with following code?
#include <stdio.h>
int main()
{
int *p = (int *)malloc(sizeof(int));
p = NULL;
free(p);
}
Answer: B
Correct answer: Memory Leak
The program allocates a block, then overwrites the only pointer to it with NULL. Nothing now holds the block's address, so it can never be freed - that is a memory leak.
Calling free(NULL) is explicitly defined to do nothing, so the last line is harmless and there is no crash and no compiler error. Nor is there a dangling pointer, which would require the pointer still to refer to freed memory. The fault is that the block was lost before it could be released.
Please log in or register to report this question.