When should a C function return newly allocated memory?

前端 未结 11 2095
陌清茗
陌清茗 2021-01-31 00:11

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

11条回答
  •  醉酒成梦
    2021-01-31 00:43

    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.

提交回复
热议问题