如何解决分段错误 wrt NULL 指针 C++
我正在尝试使用循环链表来解决约瑟夫斯问题。但是在创建函数中,我遇到了关于指向链表节点的 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,1);
execution(L,n);
return 0;
}
解决方法
您的问题就在这里:
llptr L,F;
L
和 F
指向什么?截至目前,它们都是 Wild Pointer。也就是说,您没有任何保证。因此,当您将它们传递给 create()
并检查 if(!L)
时,它将为 false,因为 L
不是 nullptr。
因此,您将尝试使用 L
取消引用 L->ptr = F;
。但同样,L
指向某个垃圾地址。这是未定义的行为。
确保将所有指针初始化为 nullptr
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。