When should a C function return newly allocated memory?

前端 未结 11 2070
陌清茗
陌清茗 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条回答
  •  梦毁少年i
    2021-01-31 00:46

    I prefer the GLib style (the 1st you mentioned). For me choosing this style makes it more object oriented like. Your methods take care of creating and destroying the struct, so you don't have to fight with the internals of a structure. This aproach leads your code to have less errors as well.

    A GString example:

    GString *s;
    s = g_string_new();
    // Not in this case, but sometimes you can
    // find this:
    if (s == NULL)
        printf("Error creating the object!");
    

提交回复
热议问题