I noticed that it is a common idiom in C to accept an un-malloc
ed pointer as a second argument instead of returning a pointer. Example:
/*function prototype*/
void create_node(node_t* new_node, void* _val, int _type);
/* implementation */
node_t* n;
create_node(n, &someint, INT)
Instead of
/* function prototype */
node_t* create_node(void* _val, int _type)
/* implementation */
node_t* n = create_node(&someint, INT)
What are the advantages and/or disadvantages of both approaches?
Thanks!
EDIT Thank you all for your answers. The motivations for choice 1 are very clear to me now (and I should point out that the pointer argument for choice 1 should be malloc'd contrary to what I originally thought).
Accepting a pointer (which the caller is responsible for malloc'ing or not) to memory to be filled in, offers serious advantages in flexibility over returning a pointer (necessarily malloc'ed). In particular, if the caller knows it needs to use whatever's returned only within a certain function, it can pass in the address of a stack-allocated struct or array; if it knows it doesn't need reentrancy, it can pass in the address of a static
struct or array -- in either case, a malloc/free pair gets saved, and such savings do mount up!-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With