title: Returning pointer to structure from function
body: <p>I was trying to return a pointer to a structure from a function. I wrote the following code but it did not work and gave a segmentation fault.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  struct Node {
      int val;
      Node* next;
      Node(int x): val(x), next(NULL) {};
  };
  
  Node* f(int a){
      Node x = Node(10);
      return &amp;x;
  }
  
  int main(){
      Node *x = f(10);
      cout &lt;&lt; x-&gt;val &lt;&lt; "\n";
      return 0;
  }
  </code></pre>
  
  <p>Whereas the following piece of code worked fine.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  struct Node {
      int val;
      Node* next;
      Node(int x): val(x), next(NULL) {};
  };
  
  Node* f(int a){
      Node *x = new Node(10);
      return x;
  }
  
  int main(){
      Node *x = f(10);
      cout &lt;&lt; x-&gt;val &lt;&lt; "\n";
      return 0;
  }
  </code></pre>
  
  <p>Why is the first code not working whereas the second one is working?</p>