gpt4 book ai didi

c++ - 1 [main] 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 说明及修复方法

转载 作者:行者123 更新时间:2023-11-28 07:45:14 26 4
gpt4 key购买 nike

尽可能简单地问任何人都可以解释为什么这个代码:

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);

最佳答案

我不能肯定地说,但是您正在访问未分配给您的内存,因此您可能越过了 myNodes 的边界。 将能够使用您的调试器确定这一点。

我可以肯定地说的是,在您调用的函数的第一行中:

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

如果 myNodes 中没有项目,那么这应该会导致访问冲突。

而且您肯定会在 for 循环中运行到 myNodes 的末尾,因为您正在访问 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());
}
}

// [...]
}

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

关于c++ - 1 [main] 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 说明及修复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15036399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com