When should a C function return newly allocated memory?

前端 未结 11 2048
陌清茗
陌清茗 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 01:00

    Having the caller allocate memory is better, because you can save memory allocations by recycling old data structures manually. This is useful in mathy applications, when you have lots of N sized arrays lying around. Remember, memory allocation is quite slow.

    On the other hand, if the size of the array can only be determined by the function (i.e. the size of the result is unknown) then the callee should allocate.

    Whatever you do, use conventions to tell people what has happened. Big stupid names like pre_allocated_N_array or new_result_array (sorry, I'm not a C expert, there should be C conventions for this though) are very handy for people who are using your function without reading the docs. It all comes down to consistency.

提交回复
热议问题