title: Pointers as function returns and use of malloc
body: <p>I am using Pointers as function returns ..below is a simple piece of code </p>
  
  <p><strong>main function:</strong>  </p>
  
  <pre><code>void main()
  {
      int a = 10, b = 20;
      int *ptr;
      ptr = add(&amp;a, &amp;b);
      printf("sum of a and b is %d\n", *ptr);
  }
  </code></pre>
  
  <p><strong>add function:</strong>   </p>
  
  <pre><code>int* add(int *a, int *b)
  {
      int c;
      c = *(a)+*(b);
      return &amp;c;
  }
  </code></pre>
  
  <p>This works correctly and gives me output  30..</p>
  
  <p>But if you add one more function <code>printhelloworld();</code> before add like below</p>
  
  <pre><code>void main()
  {
      int a = 10, b = 20;
      int *ptr;
      ptr = add(&amp;a, &amp;b);
  
      printhelloworld();--this just prints hello world
  
      printf("sum of a and b is %d\n", *ptr);
  }
  </code></pre>
  
  <p>output will not be 30 any more and it is undefined due to stack frame getting freed..so I have to modify my program like below using <code>malloc()</code></p>
  
  <pre><code>int* add(int *a, int *b)
  {    
      int* c = (int*)malloc(sizeof(int));
      *c = *(a)+*(b);
      return c;
  }
  </code></pre>
  
  <p>This works.</p>
  
  <p>But if I don't free memory allocated in heap, won't it stay forever  ? Should I not use <code>free()</code> like below ?</p>
  
  <pre><code>free(c);
  </code></pre>
  
  <p>If I use <code>free()</code> in main,<code>c</code> is not in scope and it won't work, if I use 'free` in add, again I will get undefined result.</p>
  
  <p><strong>ASK:</strong><br>
  What is the correct way to use <code>free()</code> in my case</p>
  
  <pre><code>free(C);
  </code></pre>
  
  <p><strong>Total program for repro</strong>  </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  
  void printhelloworld()
  {
  
      printf("hello world\n");
  }
  
  int* add(int *a, int *b)
  {
  
      int* c = (int*)malloc(sizeof(int));
  
      *c = *(a)+*(b);
      //free(c);
      return c;
  }
  
  
  int main()
  {
  
      int a = 10, b = 20;
  
      int *ptr;
      ptr =(int*) malloc(sizeof(int));
      ptr = add(&amp;a, &amp;b);
  
  printhelloworld();
  printf("sum of a and b is %d\n", *ptr);
  
  }
  </code></pre>