What is the problem with the following C program snippet?
IBM technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the problem with the following C program snippet?
int *p = (int *) malloc(sizeof(int));
p = NULL;
free(p);
Pick ONE option
Show answer & explanation
Answer: B. Memory Leak
The memory allocated by malloc() is lost when p is set to NULL without first freeing it. The original address is overwritten, so the allocated memory can never be deallocated, causing a memory leak. Calling free(NULL) is safe in C and does nothing—it's not a compile-time error or run-time exception.
Step-by-step Derivation:
Line-by-line trace:
malloc(sizeof(int))allocates memory on the heap and returns an address (e.g., 0x1000)p = NULL;overwrites the pointer, losing the reference to the allocated memory at 0x1000free(p);calls free(NULL), which is defined in C to be a no-op (safe, no error)- Result: The memory at 0x1000 remains allocated but unreachable—this is a memory leak. Option A is incorrect because free(NULL) is legal and produces no compile-time error. Options C and D are incorrect because the code runs without exception or dangling pointers.