1 [main] 972 exception :: handle:异常:STATUS_ACCESS_VIOLATION说明以及如何修复

时间:2013-02-23 02:39:07

标签: c++ function object pointers

尽可能简单地询问是否可以解释为什么这个代码:

LinkedListByGrade::LinkedListByGrade(vector<Node> myNodes) {
int lowestGradeFound = myNodes[0].getGrade();
Node *pFristNode = new Node();
cout << "New node created" << endl;
for (size_t i = 0; i <= myNodes.size(); i++) {
    if (myNodes[i].getGrade() < lowestGradeFound) {

        cout << "if triggered" << endl;
        lowestGradeFound = myNodes[i].getGrade();
        pFristNode->reassasignNode(myNodes[i].getFristName(),
                myNodes[i].getLastName(), myNodes[i].getId(),
                myNodes[i].getGrade());
        cout << "int reassassigned" << endl;
    }

给我这个错误:

1 [main] Project 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 
2130 [main] Project 972 open_stackdumpfile: Dumping stack trace to Project.exe.stackdump

以及如何解决它的想法?

(抱歉,我留在诊断打印报表中。)

这也是影响myNodes的唯一代码:

vector<Node> Students;
Node node1("Bobby", "zilch",28,55);
Node node2("Evil", "Dentist",308,55);
Node node3("Raz", "Buton",10,55);
Students.push_back(node1);
Students.push_back(node2);
Students.push_back(node3);

cout<<"stuff"<<endl;
 LinkedListByGrade myList = LinkedListByGrade(Students);

1 个答案:

答案 0 :(得分:1)

我不能肯定地说,但是您正在访问未分配给您的内存,因此您可能正在myNodes的边界上运行。 将能够使用您的调试器来确定此

我可以肯定地说,在你的功能的第一行,你打电话:

int lowestGradeFound = myNodes[0].getGrade();

如果myNodes中没有项目,则会导致访问冲突。

由于您正在访问myNodes,因此您肯定会在for循环中myNodes[myNodes.size()]结束。

尝试这样的事情:

LinkedListByGrade::LinkedListByGrade(vector<Node> const& myNodes) {
    // Pass by const-reference! ------------------^

    // Set this to something high. Don't access the vector, in case there are no
    // elements therein:
    int lowestGradeFound = std::numeric_limits<int>::max();

    // Where is this deleted?
    Node *pFirstNode = new Node();

    // Use iterators, not indices for looping over a container...
    for (vector<Node>::iterator i = myNodes.begin(), end = myNodes.end(); != end; ++i)
    {
        // Access element by `i->`
        if (i->getGrade() < lowestGradeFound)
        {
            // Now you can assign this safely...
            lowestGradeFound = i->getGrade();
            pFirstNode->reassasignNode(
                i->getFirstName(),
                i->getLastName(),
                i->getId(),
                i->getGrade());
        }
    }

    // [...]
}

但你真的,真的需要学会使用你的调试器!