When should a C function return newly allocated memory?

前端 未结 11 2064
陌清茗
陌清茗 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:42

    If you allocate your memory yourself, you have control over how you do that. Either in stack, standard malloc or one of the sixteen memory managers you use in your application.

    If memory is allocated for you not only you have no control over how it's done, but you should be aware of how to free the memory. Well, most of the libraries would provide you a "free" function for free.

    Having said that I still don't think there's one "nicer" approach. What suits your use better.

提交回复
热议问题