-1

My code is below, and my problem occurs when I am trying to "loadFile" through my program. It asks me for the filename, and when I give it a filename that it can find, it just says "Segmentation Fault" and stops running. I think the problem is either coming from the loadFile method itself or on line 244 which is where I'm writing the method for adding an element to the linkedlist. Any help is appreciated! Thanks.

http://pastebin.com/7qZY9Hef

Line 224:

 void countyElectionList::push_back(countyElectionResults * newCER){

    if(head == NULL)
head = newCER;
else
    {
    countyElectionResults * current = head;
    while(current->getNextResult() != NULL){
        current = current->getNextResult();
    }
current->setNextResult(newCER);
}

    }
4

2 回答 2

2

根据您链接的 URL 上的源代码(由于多种原因,包括缺少括号和缺少返回语句的函数等),问题出在此处:

// A constructor that initializes the private data members
countyElectionList::countyElectionList(){

}

你永远不会初始化countyElectionList::head为 NULL,所以当你调用countyElectionList::push_back的值head很可能不会指向 NULL 而是指向谁知道什么......因此崩溃。

供将来参考:当您调试崩溃时,如果发生崩溃的函数看起来不可疑,并且您无法找到源代码的错误并逐步执行逻辑,您应该继续检查函数的调用者。

更新:因此,在检查了您的新 pastebin 代码(仍然无法编译,因为几个声称返回值的函数缺少返回语句)之后,错误继续出现在同一个函数中:

// A constructor that initializes the private data members
countyElectionList::countyElectionList(){
    countyElectionList::head == NULL;
}

请注意,您使用==的是比较运算符不是赋值运算符,即=. 这是要使用的正确代码:

// A constructor that initializes the private data members
countyElectionList::countyElectionList(){
    head = NULL;
}

我不得不怀疑你是否真的试图编译这段代码。我做到了,我的编译器立即向我指出了错误。它甚至告诉我该怎么做:

test.cpp(210) : 警告 C4553: '==' : 运算符无效;你打算'='吗?

我也怀疑你是在你的头上。我假设这是家庭作业,并且您没有进行实际的选举系统(尽管...),所以我想我的下一个问题是:您是否考虑过与您的教授交谈并解释您对语言的语法有什么困难? 也许你的学校有资源可以提供帮助。尝试通过在文件中随机插入内容来进行编程并不能帮助您学习;这是一种沮丧的练习。

于 2012-12-05T02:01:57.587 回答
0

好吧,首先,您似乎从未在构造函数中初始化head为. NULLcountyElectionList

当您稍后尝试使用时,这可能会导致问题head,例如在countyElectionList::push_back.

于 2012-12-05T01:56:28.240 回答