C | Dynamic Memory Allocation | Question 3
Output?
# include<stdio.h> # include<stdlib.h> void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf("%d\n",*p); return(0); } |
chevron_right
filter_none
(A) May not work
(B) Works and prints 6
Answer: (A)
Explanation: The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer.
This is because fun() makes a copy of the pointer, so when malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing to random memory before and after the call to fun(), and when you dereference it, it will crash.
If you want to add memory to a pointer from a function, you need to pass the address of the pointer (ie. double pointer).
Recommended Posts:
- C | Dynamic Memory Allocation | Question 5
- C | Dynamic Memory Allocation | Question 8
- C | Dynamic Memory Allocation | Question 2
- C | Dynamic Memory Allocation | Question 1
- C | Dynamic Memory Allocation | Question 8
- C | Dynamic Memory Allocation | Question 6
- C | Dynamic Memory Allocation | Question 7
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- How to restrict dynamic allocation of objects in C++?
- MCQ on Memory allocation and compilation process
- IPC through shared memory
- How are variables scoped in C - Static or Dynamic?
- Memory Layout of C Programs
- How to deallocate memory without using free() in C?
- What is Memory Leak? How can we avoid?



