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 strcpy is a “nicer”
function, in my opinion, than strdup.
I can see how this is a valid pattern, but why might it be considered nicer? Are there advantages to following this pattern? Or not?
example
Recently I’ve written a fair amount of code that looks something like:
struct foo *a = foo_create();
// do something with a
foo_destroy(a);
If foo is a anything more than a flat structure, then I figured I could put all my initialization in one step. Also, assume the struct should be on the heap. Why might it be better form to do something like:
struct foo *a = malloc(sizeof(foo));
foo_init(a);
// do something with a
foo_destroy(a)
Whenever you want an opaque structure and don’t want to expose its internals in the header file. Your
foo_create()example illustrates this.Another example is the Windows API. E.g.
CreateWindowgives you aHWND. You have no idea what the actualWNDstructure looks like and can’t touch its fields.Same with kernel object handles. E.g.
CreateEventgives aHANDLE. You can only manipulate it with the well-defined API, and close it withCloseHandle().Re:
This requires you to define
struct fooin a header, and hence expose its internals. If you want to change it down the track, you risk breaking existing code that (incorrectly) relied on its members directly.