title: Is it safe to return a struct in C or C++?
body: <p>What I understand is that this shouldn't be done, but I believe I've seen examples that do something like this (note code is not necessarily syntactically correct but the idea is there)</p>
  
  <pre><code>typedef struct{
      int a,b;
  }mystruct;
  </code></pre>
  
  <p>And then here's a function</p>
  
  <pre><code>mystruct func(int c, int d){
      mystruct retval;
      retval.a = c;
      retval.b = d;
      return retval;
  }
  </code></pre>
  
  <p>I understood that we should always return a pointer to a malloc'ed struct if we want to do something like this, but I'm positive I've seen examples that do something like this. Is this correct? Personally I always either return a pointer to a malloc'ed struct or just do a pass by reference to the function and modify the values there. (Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten).</p>
  
  <p>Let's add a second part to the question: Does this vary by compiler? If it does, then what is the behavior for the latest versions of compilers for desktops: gcc, g++ and Visual Studio?</p>
  
  <p>Thoughts on the matter?</p>