My C++ code
#include <iostream>
#include <cstdlib>
using namespace std ;
struct Node {
int data ;
struct Node* next;
};
Node* Insert(Node *head,int data);
int main(){
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 7;
head->next = second;
second->data = 17;
second->next = third;
third->data = 37;
third->next = NULL;
head = Insert(head,3);
}
Node* Insert(Node *head,int data)
{
while (true)
{ cout << "hey" ;
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
head = head->next ;
}
return head;
}
I am tring to learning Linked List in C++. I am passing a head and data to insert in the node using Insert()
function that i have defined.
My output to terminal
Segmentation fault (core dumped)
I think i am invocating Insert()
function in a wrong way. Please Help ! Thanks !
The problem lies in this part of your code:
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
First you check if head is NULL, and if head is NULL you try to dereference ( head->data
) the head pointer, which is undefined behaviour and leads to a segfault in your case.
I propose the following algorithm:
if(head == NULL) {
Node* newHead = new Node();
newHead->data = data;
newHead->next = NULL;
return newHead;
}
while(head->next != NULL) head = head->next;
head->next = new Node();
head->next->data = data;
head->next->next = NULL;
return head;
You are missing out that head
is NULL
when it enters you if statement.
This should fix it:
Node* Insert(Node *head,int data) {
while (head != NULL) {
if (head->next == NULL) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data ;
newNode->next = NULL ;
head->next = newNode;
head = newNode;
break ;
}
head = head->next ;
}
return head;
}
Something is wrong here:
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
If head
is NULL
, so you can't assign data
to its head->data
. This causes SIGSEGV.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.