Question: In C, it is possible for functions to return pointers to memory that that function dynamically-allocated and require the calling code to free it. It's also common to require that the calling code supplies a buffer to a second function, which then sets the contents of that buffer. For example:

```
struct mystruct {
   int a;
   char *b;
};

struct mystruct *get_a_struct(int a, char*b)
{
    struct mystruct *m = malloc(sizeof(struct mystruct));
    m->a = a;
    m->b = b;

    return m;
}

int init_a_struct(int a, char*b, struct mystruct *s)
{
    int success = 0;
    if (a < 10) {
        success = 1;
        s->a = a;
        s->b = b;
    }

    return success;
}

```

Is one or the other method preferable? I can think of arguments for both: for the get\_a\_struct method the calling code is simplified because it only needs to *free()* the returned struct; for the init\_a\_struct method there is a very low likelihood that the calling code will fail to *free()* dynamically-allocated memory since the calling code itself probably allocated it.

Answer: 
I think that providing the already allocated struct as an argument is preferable, because in most cases you wouldn't need to call malloc/calloc in the calling code, and therefore worrying about free'ing it. Example:

```
int init_struct(struct some_struct *ss, args...)
{
    // init ss
}

int main()
{
    struct some_struct foo;
    init_struct(&foo, some_args...);
    // free is not needed
} 

```
I agree with other answers that passing the allocated `struct` is preferred, but there is one situation where returning a pointer may be preferred.

In case you need to explicitly free some resource at the end (close a file or socket, or free some memory internal to the struct, or join a thread, or something else that would require a destructor in C++), I think it may be better to allocate internally, then returning the pointer.

I think it so because, in C, it means some kind of a contract: if you allocate your own `struct`, you shouldn't have to do anything to destroy it, and it be automatically cleared at the end of the function. On the other hand, if you received some dynamically allocated pointer, you feel compelled to call something to destroy it at the end, and this `destroy_a_struct` function is where you will put the other cleanup tasks needed, alongside `free`.