奇怪的分割错误,在使用cout时消失

Weird segmentation fault that disappears on using cout

本文关键字:cout 消失 分割 错误      更新时间:2023-10-16

我正在尝试一个基本程序,该程序将随机初始化一个链表,并在用户指定的索引(getnth)处打印值。然而,我遇到了一个奇怪的分段错误,当我注释掉一个特定的cout行时,它就会出现,当我取消注释时就会消失。

#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
    int x;
node *next;
};
void ins(struct node*& headRef, int n)
{
    node *newNode = new node;
if (!newNode)
    return;
newNode->x = n;
if (!headRef)
    newNode->next = NULL;
else
    newNode->next = headRef;
headRef = newNode;
cout<<"n"<<n<<" inserted at "<<headRef<<"nn";
}
void disp(struct node* head)
{
    node *temp = head;
    if (!temp)
{
    cout<<"nnLL emptyn";
    return;
}
while (temp)
{
    cout<<temp->x<<" ";
    temp = temp->next;
}
cout<<"nn";
}
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
    if (i == n)
    {
        cout<<"n"<<temp->x<<"nn";
        return;
    }
}
cout<<"nIndex too highn";
}
int main()
{
node *head;
int i;
srand(time(NULL));
for (i=0; i<10; i++)
{
    ins(head, rand()%10+1);
    cout<<"Main head is "<<head<<"n"; // segfault appears if this line is commented out, disappears if it's not
}
cout<<"nInitial LLnn";
disp(head);
cout<<"nEnter index ";
cin>>i;
getnth(head, i);
return 0;
}

main中初始化

node *head=NULL;

并且你的getnth是错误的,修复它。

可能是这样的:-

void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
    if (++i == n)
    {
        cout<<"n"<<temp->x<<"nn";
        return;
    }
    temp=temp->next;
}
cout<<"nIndex too highn";
}

默认情况下,"main()"中的指针"head"是用垃圾初始化的,因为它是在程序堆栈上分配的自动变量。

因此,当您将指针"head"传递给函数"disp()"时,该指针将被取消引用,并导致分段错误。

您必须显式地用0初始化指针"head",这将解决问题。