# Segmentation fault

This is a discussion on Segmentation fault within the C++ Programming forums, part of the General Programming Boards category; Below is the code for segregating odd and even nodes of linked list such that the even nodes come before ...

1. ## 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;
int delNode(NODEPTR *);
struct node * segregateOddAndEven(struct node *head);

int main()
{

}

{

NODEPTR newNode,p;
newNode=(struct node*)malloc(sizeof(struct node));

{
newNode->data=x;
}
else
{
while(p->next)
p=p->next;

newNode->data=x;
newNode->next=p->next;
p->next=newNode;
}

}

{
{
}

}

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;
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;
}```

While running I am getting segmentation fault. Please let me know what is going wrong...

2. 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.

3. 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!

4. 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.