Reputation: 22011
If I want to return a pointer from a function, what would be better and safer?
void pro_register_application(WNDCLASS* wc); /* use wc in function */
or
WNDCLASS* pro_register_application(void)
{
WNDCLASS* wc = malloc( sizeof(WNDCLASS) );
...
return wc;
}
Upvotes: 1
Views: 48
Reputation: 3431
If you choose to have your function create a data structure and return a pointer (your second way, up there), the caller has to know HOW you allocated the space for it... did you use malloc(), or GlobalAlloc(), or some other mechanism?... and then use the corresponding method to get rid of the thing. That's sufficient reason to make the client allocate the space and pass in a pointer, to my mind.
That said, I wouldn't kill anybody for using either method, if they'd taken appropriate care to deallocate the memory correctly.
This is one of the reasons that COM objects are useful-- the client doesn't have to know how an object was created, it just has to call Release() when it's done.
Upvotes: 1
Reputation: 206518
As long as you appropriately doccument the details of ownership of the buffer being handled both are same and which one to choose depends on matter of choice.
Users of the second sample would need to be clearly told that the ownership of the buffer is transferred to them and so is the responsibility of deallocating it.
Upvotes: 3