C | Dynamic Memory Allocation | Question 3
May not work
Works and prints 6
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).
Quiz of this Question
Please comment below if you find anything wrong in the above post
My Personal Notes arrow_drop_up
Please Login to comment...