pointer as second argument instead of returning pointer?

后端 未结 7 421
长情又很酷
长情又很酷 2021-01-18 05:33

I noticed that it is a common idiom in C to accept an un-malloced pointer as a second argument instead of returning a pointer. Example:

/*functi         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 06:09

    I usually prefer receiving pointers (property initialized) as function arguments as opposed to returning a pointer to a memory area that has been malloc'ed inside the function. With this approach you are making explicit that the responsibility of memory management is on the user's side.

    Returning pointers usually leads to memory leaks, as it's easier to forget to free() your pointers if you didn't malloc()'ed them.

提交回复
热议问题