What is the correct / preferred way to allocate memory in the C API?
First I see two options:
1) Let the calling program do all the (external) memory processing:
myStruct *s = malloc(sizeof(s)); myStruct_init(s); myStruct_foo(s); myStruct_destroy(s); free(s);
The _init and _destroy necessary because more memory can be allocated inside it, and it needs to be processed somewhere.
This has the disadvantage that it is longer, but in some cases it is also possible to exclude malloc (for example, a structure distributed over stacks may be passed to it:
int bar() { myStruct s; myStruct_init(&s); myStruct_foo(&s); myStruct_destroy(&s); }
In addition, the caller needs to know the size of the structure.
2) Hide malloc in _init and free in _destroy .
Advantages: shorter code, as functions will still be called. Completely opaque structures.
Disadvantages: it is impossible to transfer the structure selected in another way.
myStruct *s = myStruct_init(); myStruct_foo(s); myStruct_destroy(foo);
I am now inclined to the first case; again, I don't know about the design of the C API.
c memory-management design api malloc
Tordek Jul 21 '10 at 4:23 2010-07-21 04:23
source share