title: Should functions that create structs return the struct or a pointer?
body: <p>I'm learning C and this is one that I can't totally figure out.  I have some code like:</p>
  
  <pre><code>typedef struct machine {
    char * name;
  } machine;
  
  machine create_machine(char * name)
  {
    Machine machine = { .name = name };
  
    return machine;
  }
  </code></pre>
  
  <p>But this means that the machine is on the stack. If the user wants it on the heap they have to create a machine themselves. So I'd need a function like this instead:</p>
  
  <pre><code>typedef struct machine {
    char * name;
  } machine;
  
  machine * init_machine(Machine * machine, char * name)
  {
    machine-&gt;name = name;
  
    return machine;
  }
  </code></pre>
  
  <p>The third option is to have <code>create_machine</code> create a machine and put it on the heap. Then also have a teardown function:</p>
  
  <pre><code>typedef struct machine {
    char * name;
  } machine;
  
  machine * create_machine(char * name)
  {
    Machine *machine = malloc(sizeof *machine);
    machine-&gt;name = name;
  
    return machine;
  }
  
  void machine_teardown(Machine * machine)
  {
    free(machine);
  }
  </code></pre>
  
  <p>I'm leaning towards the 2nd pattern here. Have a <code>create_machine</code> that returns a machine, but then also provide an "init" function that can be called. This gives the consumer the option of putting it either on the stack or the heap.</p>
  
  <p>Does this sound like a reasonable conclusion? What is the pattern that most libraries take here?</p>