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)
struct RedBlackTree RedBlackTree_new()
struct RedBlackTree tree;
tree.root = NULL;
tree.size = 0;
The real difference is the lifetime of the object. An object allocated on heap through dynamic allocation (
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.