【问题标题】:C/Linux pointers and file reading - Segmentation fault?C/Linux 指针和文件读取 - 分段错误?
【发布时间】:2018-09-27 01:49:52
【问题描述】:

在 Linux 环境中自学 C 语言,并编写了一些代码来读取/写入文件。该程序可以编译,但是当我运行它时,我得到一个“分段错误”。这就是我得到的所有信息;我什至不知道我的代码中的错误来自哪里。

由于我是 C 新手,我立即去 google:"Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you."

这是有道理的,很多示例here 显示了一些常见错误,主要与指针变量有关。我已经检查了我的代码几次,但似乎无法找到我在哪里非法访问内存。有更好的 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-&gt;value) ==> fscanf(f,"%d",&amp;line-&gt;value)。无关,在 C 中,main 应该总是返回int
  • 你的编译器没有警告你?它应该。如果使用 gcc 或 clang,请始终使用-Wall -Wextra 进行编译,以帮助解决很多问题。

标签: c segmentation-fault


【解决方案1】:

问题在于声明 fscanf(f,"%d",line-&gt;value)fscanf 需要一个 int 的地址,但你给它的是一个实际的整数。这是段错误,因为它将该 int 视为内存位置并尝试写入它。改为fscanf(f,"%d",&amp;(line-&gt;value)),它应该可以工作。

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2016-02-24
    • 2013-03-15
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多