c++ - 关于 NULL 指针的段错误 C++

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

我正在尝试使用循环链表来解决 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;
}

最佳答案

您的问题就在这里:

llptr L, F;

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

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

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

关于c++ - 关于 NULL 指针的段错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65565506/

相关文章:

c++ - 预增量运算符的放置在这里会有所不同吗?

java - 链表迭代器抛出并发修改异常

java - 链表串联

java - 链表上的递归 : how to compare?

c++ - 段错误 : 11 when popping a vector in C++

c - 读取简单 CSV 文件时出现段错误 - C

c++ - .NET 程序集在运行时初始化

c++ - LAPACKE 特征解不准确。如何改进?

c++ - 错误 : incompatible types in assignment of 'int' to 'char [1]' in GEANY

c - 在简单循环中获取段错误