When should a C function return newly allocated memory?

前端 未结 11 2050
陌清茗
陌清茗 2021-01-31 00:11

In a response elsewhere, I found the following snippet:

In general it is nicer in C to have the caller allocate memory, not the callee - hence why str

11条回答
  •  醉梦人生
    2021-01-31 00:47

    Both approaches are perfectly fine. Consider all the FILE* manipulation functions, they're not allowing you to allocate a FILE yourself.

    If you're programming in C, you'd often want full control of everything. That means giving the caller the control over where and how to allocate the structure is a good thing. Personally I usually create 2 functions for initalization if I'm not needing an opaque struct

    int foo_init(struct foo *f); // allows the caller to allocate 'f' 
                                 //however is suitable
    struct foo * new_foo(void);  // mallocs and calls foo_init, for convenience.
    

    And if needed, corresponding

     void foo_free(struct foo *f );   //frees and destroys 'f'
     void foo_destroy(struct foo *f); //cleans up whatever internal stuff 'f' has,
                                      // but does not free 'f' itself
    

    In cases where you want the caller to treat the structure as opaque, you'll only provide a struct foo* new_foo(void); Not exposing the struct foo implementation has some benefits:

    • Caller arn't allowed to poke around or perform potential dangerous shortcuts by accessing the members directly.
    • You can change struct foo without breaking existing binaries (you're not breaking the ABI), can be a big deal if you're implementing a library.
    • Your public header file don't need to expose the implementation and other required headers for struct foo

    The drawbacks

    • The caller has no control over the allocation of a struct foo
    • You'll have the overhead of always having to manipulate a struct foo through function calls

提交回复
热议问题