This is somewhat of a subjective question, but it seems like there should be a standard for this. I'm making a tree-like data structure, and I want to know the best way to pass new nodes from a function. I've had several ideas, but I don't know which is safest/most efficient.
Here's a simplification of my code:
typedef struct Node {
struct Node *left;
struct Node *right;
int value;
} Node;
int f() {
//do stuff
}
Node *new_node() {
Node n = {NULL, NULL, f()};
return &n;
}
int main() {
Node a = {new_node(), new_node(), 0};
}
Obviously, this doesn't work, because the pointer returned by the new_node()
function points to stack-allocated data that will be released as soon as new_node()
ends. But what is the best way to get around that?
One possibility would be to allocate n
on the heap, like this:
Node *new_node() {
Node *n = (Node *) malloc(sizeof(Node)); //unsure if the cast is necessary here, but that's not relevant
n->left = NULL;
n->right = NULL;
n->value = f();
return n;
}
This feels off though, because it requires that the caller function handle memory clearing directly, which could get messy fast.
Another option I've seen (especially when the object is an array or buffer, rather than an object) is to pass a pointer to the function, and just modify the contents of the pointer.
void new_node(Node *n) {
n->left = NULL;
n->right = NULL;
n->value = f();
}
int main() {
Node n = {NULL, NULL, 0};
Node n1 = n;
new_node(&n);
new_node(&n1);
Node a = {&n, &n1, 0};
}
Or you could just pass the data directly, especially since Node
is so small in this case:
Node new_node() {
Node n = {NULL, NULL, f()}
return n;
}
That seems like it would be slower, though I don't know for sure.
There are a few answers about this topic already, but they are in C++ and deal with both references and pointers, which I'm afraid I don't really understand the difference between.
What is the standard way to do this?
(Sorry this if this is too long)