These lines
Node* temp = (Node*)malloc(sizeof(Node));
temp = list->head;
produces a memory leak. At first a memory was allocated and its address was stored in the pointer temp
and then the value of the pointer temp
was overwritten by the value of the expression list->head
. As a result the address of the allocated memory was lost.
After this loop
while(temp != NULL)
{
temp = temp->next;
}
the pointer temp
is equal to NULL
. So a null pointer is used to access memory in these statements
temp->data = value;
temp->next = NULL;
that invokes undefined behavior.
The function can be defined for example the following way.
int appendItem( LinkedList *list, int value )
{
Node *new_node = malloc( sizeof( Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = value;
new_node->next = NULL;
if ( list->head == NULL )
{
list->head = new_node;
}
else
{
Node *current = list->head;
while ( current->next != NULL ) current = current->next;
current->next = new_node;
}
}
return success;
}
Pay attention to that the memory allocation can fail. You need to process such a case in your function. And the caller of the function should be informed about such a situation.
Also as you allow to append new nodes to a singly-linked list then the list should be defined as a two-sided singly-linked list. That is the list should keep two pointers: one pointer to the head node and other pointer to the tail node. Otherwise appending a node to the list will be inefficient.