Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer as second argument instead of returning pointer?

Tags:

c

pointers

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:

/*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).

like image 327
Tyler Avatar asked Mar 26 '10 02:03

Tyler


1 Answers

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!-)

like image 125
Alex Martelli Avatar answered Oct 06 '22 09:10

Alex Martelli