奇怪的分割错误,在使用cout时消失
Weird segmentation fault that disappears on using cout
我正在尝试一个基本程序,该程序将随机初始化一个链表,并在用户指定的索引(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",这将解决问题。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- 将地址分配给本地指针后,公共对象的变量将消失
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- std::cout输出int时出现编译错误
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- C++ Setter/Getter,cout 工作,printf 失败
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 应用投影矩阵后对象消失
- 结构元素名称要 cout?
- 使用模板类重载 cout
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- 我收到一个断言错误,但是当我编写 cout 语句时,它会消失
- 奇怪的分割错误,在使用cout时消失
- 为什么std::cout输出在发送NULL后完全消失?