Hatefiend
Hatefiend

Reputation: 3596

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)
        error(DS_MSG_OUT_OF_MEM);
    return tree 
}

VS.

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 adestroy function for my Tree, I wouldn't be able to free the memory allocated from structures within the RedBlackTree if they weren't created with malloc or calloc right?

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.

Upvotes: 0

Views: 934

Answers (2)

qcc
qcc

Reputation: 1

firstly it's better to use typedef. it's easier.

if u create an object dynamically, u need to free every member of the object urself. or, the memory leak.

if it is a big struct , when u return it, it create a temp object. it cost more. so I prefer pointer! and forget what i say before. I just sleepwalking.

Upvotes: -4

Jack
Jack

Reputation: 133567

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 has automatic storage, 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.

Upvotes: 5

Related Questions