[英]C/Linux pointers and file reading - Segmentation fault?
在Linux环境中进行C语言自学的工作,并编写了一些从文件读取/写入的代码。 该程序可以编译,但是当我运行它时,会出现“分段错误”。 这就是我得到的所有信息; 我什至不知道错误来自哪里。
由于我是C语言的新手,所以我立即去Google: "Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you."
这是有道理的,并且这里的许多示例都显示了一些常见的错误,大部分与指针变量有关。 我已经检查了几次代码,但是似乎找不到我非法访问内存的位置。 懂C的人可以帮助我找到我的错误,也许还可以更好地解释它是如何导致细分错误的吗?
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *next;
} node;
void insert(struct node*);
struct node * head = NULL;
void main(int argc, char * argv[])
{
if(argc!=3)
{
printf("Please provide the input and output text file names as %s name1 name2\n", argv[0]);
return;
}
FILE *f;
if(!(f=fopen(argv[1], "r")))
{
printf("Input file %s cannot be opened.\n", argv[1]);
return;
}
struct node * line = (struct node*)malloc(sizeof(struct node));
if(line==NULL)
{
printf("Cannot do dynamic memory management.\n");
return;
}
while(fscanf(f,"%d",line->value)!=EOF)
{
printf("%d ",line->value);
line->next=NULL;
insert(line);
line=(struct node*)malloc(sizeof(struct node));
if(line==NULL)
{
printf("Cannot do dynamic memory management.\n");
return;
}
}
free(line);
printf("content:\n");
while(head!=NULL)
{
line=head;
head=head->next;
printf("%d ",line->value);
free(line);
}
fclose(f);
}
void insert(struct node * element)
{
struct node * temp = head;
struct node * pretemp = NULL;
while(temp!=NULL && temp->value > element->value)
{
pretemp=temp;
temp=temp->next;
}
if(pretemp==NULL)
{
element->next=head;
head=element;
}
else
{
pretemp->next=element;
element->next=temp;
}
}
问题出在语句fscanf(f,"%d",line->value)
。 fscanf
需要一个int的地址,但是您给它一个实际的整数。 这是段错误,因为它将int视为内存位置并尝试写入它。 改为fscanf(f,"%d",&(line->value))
,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.