返回指向动态分配结构的指针与需要从调用函数分配内存?

nsg*_*nsg 5 c memory struct

在 C 中,函数可以返回指向该函数动态分配的内存的指针,并要求调用代码释放它。要求调用代码向第二个函数提供缓冲区也是很常见的,然后第二个函数设置该缓冲区的内容。例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

哪种方法更可取?我可以想到两者的论据:对于 get_a_struct 方法,调用代码被简化,因为它只需要free()返回的结构;对于 init_a_struct 方法,调用代码无法free()动态分配内存的可能性非常低,因为调用代码本身可能分配了内存。

小智 1

我认为提供已分配的结构作为参数更好,因为在大多数情况下,您不需要在调用代码中调用 malloc/calloc,因此担心释放它。例子:

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
} 
Run Code Online (Sandbox Code Playgroud)