Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C | Dynamic Memory Allocation | Question 2

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Consider the following three C functions :




[PI] int * g (void
  int x= 10; 
  return (&x); 
}  
    
[P2] int * g (void
  int * px; 
  *px= 10; 
  return px; 
    
[P3] int *g (void
  int *px; 
  px = (int *) malloc (sizeof(int)); 
  *px= 10; 
  return px; 
}


Which of the above three functions are likely to cause problems with pointers? (GATE 2001)
(A) Only P3
(B) Only P1 and P3
(C) Only P1 and P2

(D) P1, P2 and P3


Answer: (C)

Explanation: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.
In P2, pointer variable px is being assigned a value without allocating memory to it.
P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.


Quiz of this Question

My Personal Notes arrow_drop_up
Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads