In the second version, you overwrite the pointer value obtained from malloc()
with NULL
and therefore cannot access this memory anymore, a situation called a memory leak: definitely not what you want.
The first version is not incorrect, but initializing the pointer to NULL
is redundant since you immediately store the return value of malloc()
into it. The compiler will probably omit this redundant store, but for readability, you can simplify it as:
struct Node *head = (struct Node*)malloc(1 * sizeof(struct Node));
Note that casting the return value of malloc
is useless in C and somewhat error prone. It is recommended to just write:
struct Node *head = malloc(1 * sizeof(struct Node));
As a matter of fact, the 1 *
is usually omitted:
struct Node *head = malloc(sizeof(struct Node));
Note that it is also error prone to use an explicit type in the malloc
argument as the C compiler will not perform any kind of consistency check between the size allocated and the pointer type. If you later change the type of head
or use a different type by mistake, the size may be incorrect. For a safer way to specify the size to allocate, use the target type of the destination pointer:
struct Node *head = malloc(sizeof(*head));
For an even safer alternative, use calloc()
that will initialize the memory to all bits 0, which on most current hardware is the zero value for integer and floating point members and the null pointer value for all pointer types. One more advantage is you can specify the number of items to allocate, as you seem to like:
struct Node *head = calloc(1, sizeof(*head)); // all members initialized to zero
In all cases, testing if the memory allocation succeeded is highly recommended:
struct Node *head = calloc(1, sizeof(*head)); // all members initialized to zero
if (head == NULL) {
fprintf(stderr, "memory allocation failed\n");
exit(EXIT_FAILURE);
}
You could further simplify the expression with sizeof *head
instead of sizeof(*head)
. These are equivalent, the parentheses are redundant. I personally omit them only for a naked identifier, as in sizeof head
, but use them for any other expression. Conversely, parentheses are required for a type, as in sizeof(struct Node)