Open In App
Related Articles

C | Dynamic Memory Allocation | Question 2

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

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!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads