分段错误 wrt NULL 指针 C++

时间:2021-01-04 15:46:22

标签: c++ linked-list segmentation-fault null-pointer josephus

我正在尝试使用循环链表来解决约瑟夫斯问题。但是在创建函数中,我遇到了关于指向链表节点的 NULL 指针的分段错误。谁能解释为什么会出现分段错误?谢谢!

#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 个答案:

答案 0 :(得分:2)

您的问题就在这里:

llptr L, F;

LF 指向什么?截至目前,它们都是 Wild Pointer。也就是说,您没有任何保证。因此,当您将它们传递给 create() 并检查 if(!L) 时,它将为 false,因为 L 不是 nullptr。

因此,您将尝试使用 L 取消引用 L->ptr = F;。但同样,L 指向某个垃圾地址。这是未定义的行为。

确保将所有指针初始化为 nullptr

相关问题