C | Dynamic Memory Allocation | Question 7
What is the problem with following code?
#include<stdio.h> int main() { int *p = (int *)malloc(sizeof(int)); p = NULL; free(p); } |
chevron_right
filter_none
(A) Compiler Error: free can’t be applied on NULL pointer
(B) Memory Leak
(C) Dangling Pointer
(D) The program may crash as free() is called for NULL pointer.
Answer: (B)
Explanation: free() can be called for NULL pointer, so no problem with free function call.
The problem is memory leak, p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be following:
free(p);
p = NULL;
Recommended Posts:
- C | Dynamic Memory Allocation | Question 3
- C | Dynamic Memory Allocation | Question 6
- C | Dynamic Memory Allocation | Question 1
- C | Dynamic Memory Allocation | Question 2
- C | Dynamic Memory Allocation | Question 8
- C | Dynamic Memory Allocation | Question 5
- C | Dynamic Memory Allocation | Question 8
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- MCQ on Memory allocation and compilation process
- How to restrict dynamic allocation of objects in C++?
- IPC through shared memory
- Memory leak in C++ and How to avoid it?
- How to deallocate memory without using free() in C?
- Memory Layout of C Programs
- What is Memory Leak? How can we avoid?

