c - 分段故障链接列表

时间:2015-10-24 03:01:19

标签: c

我正在做一个项目学习C中的链表。当我的代码编译时,我在尝试运行我的代码时遇到分段错误。我知道分段错误发生在哪里,但我试图弄清楚它有什么问题。这是我的代码:

//
// It reads the list from the file_name indicated. If the list already has entries,
// it will clear the entries.
//
int llist_read(LinkedList * list, char * file_name) {
        //Still Need to complete this!!!
        ListNode * e;
        int val;
        FILE *f;

        e = list->head;
        while (e != NULL) {
            e->value = 0;
            e = e->next;
        }
        e = list->head;
        if (file_name == NULL) {
                return 0;
        }
        if ((f = fopen(file_name, "r")) == NULL) {
                return 0;
        }
        if (fscanf(f, "%d\n", &val, val) == 0) {
                return 0;
        }
        else {
            e->value = val; //Segmentation Fault occurs here.
            e = e->next;
            e = fscanf(f, "%d", e->value);
            while (e->next = fscanf(f, "%d", e->value) != EOF) {

            }
    }
    return 1;
}

我在这里遇到了分段错误:

e->value = val; //Segmentation Fault occurs here.

对于为什么这不起作用的任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

在为e->value分配值之前,您应该检查是否有分配给e的内存。将赋值语句替换为:

if ( e )
{
    e->value = val;
    e = e->next;
    fscanf ( f, "%d", &(e->value) );
}

您必须在此if语句中解析循环。