Reputation: 73
I'm implementing a singly linked list using C.
struct Node
{
int nodeValue;
struct Node* pNext;
};
struct Node* head;
void createList()
{
head = (struct Node*)malloc(sizeof(struct Node));
}
void insertNodeAtBeginning(int value)
{
struct Node* newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->nodeValue = value;
struct Node* auxNode;
if(head->pNext == NULL)
{
head->pNext = newNode;
}
else
{
auxNode = head->pNext;
head->pNext = newNode;
newNode->pNext = auxNode; //breakpoint set here
}
}
I've set a breakpoint on line marked by the comment. The value of auxNode is non-NULL:
(gdb) p auxNode
$4 = (struct Node *) 0x5555555551db <createList+18>
However the value of newNode->pNext to which the auxNode is assigned is NULL:
(gdb) p newNode->pNext
$5 = (struct Node *) 0x0
Could anyone clarify this behavior? Thanks.
Upvotes: 1
Views: 58
Reputation: 65
It appears that you want to maintain your head node, but insert between the head node and the node after the head node, correct? If that is the case, then aside from a misleading function name (perhaps insertNodeAfterHead would be more appropriate), you should initialize your head struct members after you allocate with malloc.
Should be...
void createList()
{
head = (struct Node*)malloc(sizeof(struct Node));
head->nodeValue = 0
head->pNext = NULL;
}
Upvotes: 0
Reputation: 311146
For starters the function createList
does not make a sense.
void createList()
{
head = (struct Node*)malloc(sizeof(struct Node));
}
You already created an empty list
struct Node* head;
Within the function data members nodeValue
and pNext
were not initialized,
The function insertNodeAtBeginning
also does not make a sense because at least it does not insert a node at beginning due to this code snippet
if(head->pNext == NULL)
{
head->pNext = newNode;
}
Moreover it invokes undefined behavior because the data member pNext
of the node pointed to by the pointer head
was not initialized. And again you forgot to initialize the data member pNext
of the new node when head->pNext
is equal to NULL
.
Remove the function createList
and define the function insertNodeAtBeginning
the following way
int insertNodeAtBeginning(int value)
{
struct Node* newNode = malloc( sizeof( struct Node ) );
int success = newNode != NULL;
if ( success )
{
newNode->nodeValue = value;
newNode->pNext = head;
head = newNode;
}
return success;
}
Upvotes: 1