When should a C function return newly allocated memory?

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

    My opinion on it is this - there are two ways to deal with this:

    If you write a function that allocates memory, write a comment above the function to indicate that the responsibility of memory management lies with the programmer i.e. explicitly free the memory, hence passing the burden of memory management to the programmer who will be responsible.

    Alternatively, write a wrapper function something like this, ending in _alloc and a corresponding wrapper function ending in _free, in that way, you are defining a well-documented set of routines which makes it easier for the programmer to read.

    The simple advantage is this: if the programmer un-intentionally introduced a memory leak, the warning is there as the adage in C is this 'For every malloc, there should be a corresponding free, if you do not have it, then you have a leak'. The programmer in turn can clue in and say "Aha..I called this wrapper function something_alloc but did not call something_free". You get the gist? And anyway, the programmer will thank you for it!

    Really, it is down to how well the code API is defined. If you want to write code to manage memory and hence free up the programmer from having the responsibility in managing memory, best to wrap it and give it a special meaning, as I have suggested like using an underscore followed by 'alloc' and 'free'.

    This will earn you kudos and respect as the programmer who will be reading and using your code will say - 'Thanks bud' and end result is everyone will be happy.

    Hope this helps, Best regards, Tom.

提交回复
热议问题