The problem
I have this structure that I want to create a "constructor" for it.
struct example {
int x, y, z; /* various members */
struct another *another; /* pointer to another structure */
}
The two different ways I know of
- Using functions that create and delete structures on heap
I can create structures by making functions that allocates them on the heap like this:
/* create example */
struct example *example_new(int x, int y, int z) {
struct example *p = malloc(sizeof *p);
p->x = x;
p->y = y;
p->z = z;
p->another = another_new();
}
/* delete example */
void example_new(struct example *p) {
another_del(p->another);
free(p);
}
- Using functions that initializes and frees memory for structure through pointer
Or I could initalize the structure by passing pointer to the function and have the user responsible for allocating and deallocating memory for it.
/* initalize example */
void example_init(struct example *p, int x, int y, int z) {
assert(p);
p->x = x;
p->y = y;
p->z = z;
p->another = another_new();
}
/* free memory allocated for example */
void example_free(struct example *p) {
another_del(p->another);
}
My thoughts
I usually prefer first approach when creating recursive structures (like Trees and Linked Lists) but use the second approach in all other cases.
I tried to use the second approach for a recursive structure and it turned out to be quite messy.
The question
How do you choose between these two ways? Is there a third way you would use to solve this problem?