-
Segmentation fault
Below is the code for segregating odd and even nodes of linked list such that the even nodes come before odd nodes.(e.g. for list 1->3->2->5->4->6 the output should be 2->4->6->1->3->5)
Code:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
typedef struct node *NODEPTR;
void addElement(struct node **head, int x);
int delNode(NODEPTR *);
void printList(struct node * head);
struct node * segregateOddAndEven(struct node *head);
int main()
{
NODEPTR head=NULL;
addElement(&head, 10);
addElement(&head, 5);
addElement(&head, 7);
addElement(&head, 12);
addElement(&head, 4);
printList(head);
head= segregateOddAndEven(head);
printList(head);
}
void addElement(NODEPTR *head, int x)
{
NODEPTR newNode,p;
newNode=(struct node*)malloc(sizeof(struct node));
if(*head==NULL)
{
newNode->data=x;
*head=newNode;
(*head)->next=NULL;
}
else
{
p=*head;
while(p->next)
p=p->next;
newNode->data=x;
newNode->next=p->next;
p->next=newNode;
}
}
void printList(struct node *head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
int delNode(NODEPTR * node)
{
NODEPTR p;
int x;
p=*node;
*node=(*node)->next;
x=p->data;
free(p);
return x;
}
struct node * segregateOddAndEven(struct node *headRef)
{
struct node *odd=NULL,*temp,**p,*prev=NULL;
p=&headRef;
while(1)
{
if(((*p)->data%2)!=0 && *p)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=(*p)->data;
temp->next=NULL;
if(odd==NULL)
odd=temp;
else
prev->next=temp;
prev=temp;
delNode(p);
}
else
{
if(!*p)
break;
p=&((*p)->next);
}
}
(*p)->next=odd;
return headRef;
}
While running I am getting segmentation fault. Please let me know what is going wrong...
-
Have you tried running it in the debugger?
Using this, you'll find the exact line of code where it crashes (so you'll know more than "it doesn't work").
Plus, you'll be able to examine all your variables to help you figure out why the pointer you tried to dereference is bad.
The debugger is a vital tool to learn how to use, and now is a really good time to start that learning.
-
I think this belongs in C and not C++. It is important to understand what C is and what C++ is - since they're two entirely different languages!
-
Code:
if(((*p)->data%2)!=0 && *p)
1st, consider the order of these two operations and what it is saying. You are asking the question "if the data pointed to by *p is even and *p is a valid pointer". Shouldn't you first ask if the pointer is valid and then ask the "is it even" question?
2nd, consider that the only way to break out of the while(1) loop in the segregateOddAndEven function is by having *p be an invalid pointer. The next statement after the loop however attempts to access *p and assigns its "next" pointer.