title: C++ Check if pointer is passed, else create one?
body: <p>Okay i've seen this done somewhere before where you have a function that takes a pointer parameter and returns a pointer.</p>
  
  <p>However you can choose not to pass a parameter and it will return a dynamically allocated pointer but if you do pass a pointer then it just fills it in instead of creating one on the heap. This is a single function not overloaded.</p>
  
  <p>My question is how is this safely done?</p>
  
  <p>I had a guess it was something like this:</p>
  
  <pre><code>point* funct(point *p = some_value)
  {
   if p == some_value
     //create a point *p on the heap
  
   else
     //create use the given *p and fill it in
  
   return p
  }
  </code></pre>
  
  <p>Now i can't think if this is right way to do it and if it is then what could be a good some_value? it can't be NULL because when you pass empty pointer it will also be NULL and not sure if it is safe to have it greater than 0. Also you can't have negative numbers on pointers either, so whats a good safe value?</p>
  
  <p>Any good way to do this that is also PORTABLE across platforms?</p>
  
  <p>EDIT:</p>
  
  <p>Okay maybe i didn't explain properly basically i want the function to be used like this:</p>
  
  <pre><code>point *x;
  point *y;
  
  x = func();
  func(y);
  </code></pre>
  
  <p>Not</p>
  
  <pre><code>x = func(NULL);
  </code></pre>
  
  <p>if I use NULL i get an error segmentation fault only when i do func(y);</p>
  
  <p>The reason for this is:</p>
  
  <p>either the user passes a pointer he manages such as one created on the stack OR the function will give a dynamic one back if none is given. I don't want to force the return of only dynamic memory or only accepting a pointer to fill.</p>
  
  <p>I know I have seen this done somewhere before.</p>