I just wanted to double check that the following was a totally okay and appreciated improvement:
If I were to have:
struct ll_Node
{
void *data;
struct ll_Node *next, *prev;
};
And I had the constructor:
static struct ll_Node* ll_Node_new(void *data)
{
struct ll_Node *node = calloc(1, sizeof(struct ll_Node));
if (node == NULL)
exit(EXIT_FAILURE);
node->data = data;
return node;
}
In the above code snippet, I want to make sure the previous
variable is set to NULL
. I heard using calloc
defaults variables to 0
in memory which in C for all intents and purposes is the exact same thing as NULL
.
So instead of:
struct ll_Node *node = malloc(sizeof(struct ll_Node));
I do
struct ll_Node *node = calloc(1, sizeof(struct ll_Node));
I ask this because calloc
seems to be extremely popular when it comes to arrays, because if you were to use malloc
for an array, the every item would have garbage data in it. Is using calloc
with a 1
in the first parameter slot considered bad coding?.
Tiny tiny subquestion: is exiting the program if the thing I use calloc
on is NULL
acceptable? Or is that a bit extreme? I figure that if there's no memory left to create a struct then clearly any hopes of my program continuing to run are forfeit.