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 str
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. CreateWindow
gives you a HWND
. You have no idea what the actual WND
structure looks like and can't touch its fields.
Same with kernel object handles. E.g. CreateEvent
gives a HANDLE
. You can only manipulate it with the well-defined API, and close it with CloseHandle()
.
Re:
struct foo *a = malloc(sizeof(foo));
This requires you to define struct foo
in 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.