Hatefiend Hatefiend - 1 month ago 4x
C Question

C - Constructor, better to return struct or pointer to struct?

I'm currently making a RedBlackTree in C and I still don't understand which one is better / more ideal when it comes to having a constuctor function for your structures.

struct RedBlackTree* RedBlackTree_new()
struct RedBlackTree *tree = calloc(1, sizeof(struct RedBlackTree));
if (tree == NULL)
return tree


struct RedBlackTree RedBlackTree_new()
struct RedBlackTree tree;
tree.root = NULL;
tree.size = 0;
return tree;

I mean, if I do the second option, then I constantly have to pass it into my functions as a pointer using
and to my knowledge, I can never destroy it until my program ends (can someone verify if that's true?). For example, if I had a
function for my Tree, I wouldn't be able to free the memory allocated from structures within the
if they weren't created with

Also in a more general case, what are the advantages and disadvantages of either? I can always retrieve the data from the pointer by using
and I can always turn my data into a pointer by using
, so it almost feels like they are completely interchangable in a sense.


The real difference is the lifetime of the object. An object allocated on heap through dynamic allocation (malloc/calloc and free) survives until it's explicitly freed.

On the contrary an object which is allocated on stack, like in your second example, survives only the scope in which it's declared and must be copied somewhere else to make it survive.

So this should help you in choosing which suits better a specific circumstance.

From an efficiency perspective dynamic allocation is more expensive and requires additional indirections but allows you to pass pointers around, which prevents data from being copied thus can be more efficient in other situations, eg. when objects are large and copies would be expensive.