Reputation: 35
I am trying to use a circular linked list to solve the Josephus problem. But in the create function I got a segmentation error regarding NULL pointer to the linked list node. Can anyone explain why there is a segmentation error? Thank You!
#include <iostream>
using namespace std;
struct llnode
{
int data;
bool life;
struct llnode *ptr;
};
typedef struct llnode *llptr;
int create(llptr &L, llptr F, int n, int c=1)
{
if(!L)
{
L = new(llnode);
if(c=1)
F = L;
L->data = c;
L->life = true;
L->ptr = NULL;
}
if(c==n)
{
L->ptr = F;
return 0;
}
create(L->ptr,F,n,1+c);
return 0;
}
int execution(llptr L,int n)
{
if(n==2)
{
cout<<"The Winner is: "<<L->data<<endl;
return 0;
}
L = L->ptr;
while(L->life == false)
L = L->ptr;
L->life = false;
while(L->life == false)
L = L->ptr;
execution(L,n-1);
return 0;
}
int main()
{
llptr L,F;
int n;
cout<<"Enter the Number of Players"<<endl;
cin>>n;
create(L,F,n,1);
execution(L,n);
return 0;
}
Upvotes: 2
Views: 143
Reputation: 15446
Your issue is right here:
llptr L, F;
What are L
and F
pointing to? As of now, they're both Wild Pointers. That is, you have no guarantee. So when you pass them to create()
and check if(!L)
, it'll be false, since L
is not nullptr.
So you'll then try to dereference L
with L->ptr = F;
. But again, L
is pointing to some garbage address. This is Undefined Behavior.
Make sure to initialize all your pointers to nullptr
.
Upvotes: 2