从代码中得到分段错误如何摆脱它? [英] Got segmentation fault from code how to get rid of it?

查看:87
本文介绍了从代码中得到分段错误如何摆脱它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试调试此程序时,它显示程序接收信号SIGSEGV,Segmentation fault。我不知道该怎么做才是我发布这个问题的原因。


我尝试了什么:



When I tried to debug this program it shows Program received signal SIGSEGV,Segmentation fault. I don't know what to do that's why I posted this question.

What I have tried:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
static int count=0;
struct node
{
	int coef;
	int pow;
	struct node *link;
};

struct node *head=NULL;

void showoff()
{
	struct node *t1;
	t1=head;
	while(t1!=NULL)
	{
		printf("|%d|%d|%x|--",t1->coef,t1->pow,t1->link);
		t1=t1->link;
	}
}

int main()
{
	int n,i=0;
	struct node *temp,*t;
	t=head;
	printf("Number of nodes\n");
	scanf("%d",&n);
	
	while(i<n)
	{
		temp=(struct node*)malloc(sizeof(struct node));
		temp->coef=NULL;
		temp->pow=NULL;
		
		if(count==0)
		{
			temp->link=head;
			head=temp;
		}
		if(count==1)
		{
			temp->link=head->link;
			head->link=temp;
		}
		if(count>1)
		{
			while(t->link!=NULL)    /*Responsible for error. Can you explain why*/
			{
				t=t->link;
			}
			temp->link=t->link;
			t->link=temp;
		}
		count++;
		i++;
	}
	showoff();
}

推荐答案

首先,您应该使用调试器来解决此问题。它会快速向您显示问题所在。如果你的编译器没有,那么就得到一个。 Visual Studio 2017社区版免费提供,即免费。



我的猜测是因为t无效而你引用了无效指针而导致错误。



尝试调整循环,以便在每次迭代中显示内容:
Firstly, you should use a debugger to fix this. It will show you quickly exactly what the problem is. If you do not have one with your compiler then get one that does. Visual Studio 2017 community edition is available at no cost ie., free.

My guess is the fault is caused because t is invalid and you are deferencing an invalid pointer.

Try adjusting your loop so you display things in every iteration :
// ...
	for( i = 0; i < n; ++i )    // I prefer a for loop for this
	{
		// ... logic goes here

		printf( "i is %d, count is %d\n", i, count );
		showoff();
		count++;
	}


尝试将以下行分成两行:

Try breaking the following line into two lines:
struct node *temp,*t;





制作:



Make it:

struct node *temp;
struct node *t;





试试吧重建并运行看看会发生什么。

我想知道结构*是否未被正确声明。



Just try that and rebuild and run see what happens.
I'm wondering if the struct * isn't being declared properly.


这篇关于从代码中得到分段错误如何摆脱它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆