I noticed that it is a common idiom in C to accept an un-malloc
ed pointer as a second argument instead of returning a pointer. Example:
/*functi
That doesn't make much sense. Pointers in C are passed by value, just like other objects—the difference lies in the value. With pointers, the value is the memory address, which is passed to the function. However, you're still duplicating the value, and so when you malloc
, you'll be changing the value of the pointer inside your function, not the one on the outside.
void create_node(node_t* new_node, void* _val, int _type) {
new_node = malloc(sizeof(node_t) * SIZE);
// `new_node` points to the new location, but `n` doesn't.
...
}
int main() {
...
node_t* n = NULL;
create_node(n, &someint, INT);
// `n` is still NULL
...
}
There are three ways to avoid this. The first is, as you mentioned, returning the new pointer from the function. The second is to take a pointer to the pointer, thereby passing it by reference:
void create_node(node_t** new_node, void* _val, int _type) {
*new_node = malloc(sizeof(node_t) * SIZE);
// `*new_node` points to the new location, as does `n`.
...
}
int main() {
...
node_t* n = NULL;
create_node(&n, &someint, INT);
// `n` points to the new location
...
}
The third is to simply malloc
n
outside the function call:
int main() {
...
node_t* n = malloc(sizeof(node_t) * SIZE);
create_node(n, &someint, INT);
...
}