2

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;
}
  • 1
    It looks like you're creating a list the "C-style" way. Is there a reason you don't build a `List` class to make it easier to guarantee that your `List` objects will always be in a good state? – scohe001 Jan 04 '21 at 15:49
  • 1
    I see an issue with `create` function, `create(L->ptr,F,n,1+c);` calling can be with `NULL` value as `L->ptr` you are setting above with `NULL` – roottraveller Jan 04 '21 at 15:52
  • As a matter of good coding practice always initialize your variables -- not just pointer varibless but *all* variables. `llptr L = nullptr; llptr F = nullptr; int n = 0;`. – R Sahu Jan 04 '21 at 17:08

1 Answers1

2

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.

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Ohhh so just initialized pointers point to random locations... Alright! So initializing the pointers as nullptr in the main function should do the trick. Also a side question... what is the difference between L = NULL and L = nullptr (where L is a pointer btw) – Ishan Joshi Jan 04 '21 at 16:15
  • 1
    @Ishan [NULL vs nullptr (Why was it replaced?)](https://stackoverflow.com/q/20509734/2602718) – scohe001 Jan 04 '21 at 16:16
  • Alright, will check it. And adding nullptr worked! Thanks a lot! – Ishan Joshi Jan 04 '21 at 16:24