[英]Segmentation Fault wrt NULL pointers C++
我正在嘗試使用循環鏈表來解決約瑟夫斯問題。 但是在創建 function 時,我收到關於指向鏈表節點的 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;
L
和F
指的是什么? 截至目前,它們都是Wild Pointers。 也就是說,你沒有任何保證。 因此,當您將它們傳遞給create()
並檢查if(!L)
時,它將是錯誤的,因為L
不是 nullptr。
因此,您將嘗試使用L->ptr = F;
取消對L
的引用; . 但同樣, L
指向一些垃圾地址。 這是未定義的行為。
確保初始化所有指向nullptr
的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.