The Wayback Machine - https://web.archive.org/web/20240118172709/https://www.geeksforgeeks.org/c-dynamic-memory-allocation-question-3/
Open In App
Related Articles

C | Dynamic Memory Allocation | Question 3

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Output? 

C




# 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",*p);
    return(0);
}


(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).


Quiz of this Question
Please comment below if you find anything wrong in the above post

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 09 Feb, 2013
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads