【问题标题】:Unhandled exception at 0x001066F6 in task2.exe: 0xC0000005: Access violation reading location 0x0000000C [closed]task2.exe 中 0x001066F6 处未处理的异常:0xC0000005:访问冲突读取位置 0x0000000C [关闭]
【发布时间】:2014-05-20 15:43:08
【问题描述】:

作为学校作业的一部分,我编写了以下代码。它根据学生 ID 对对象指针数组进行排序,这是一个介于 100 和 999 之间的私有 int。但由于某种原因,我在 VS12 中调试时 getId 函数出现以下错误:

Unhandled exception at 0x001066F6 in task2.exe:
0xC0000005: Access violation reading location 0x0000000C.

这是使用getId的代码:

if (nr_of_students > 1) {
    int pre = nr_of_students - 1;
    int current = nr_of_students;
    Student* temp;
    // This pause will run:
    system("pause");
    while (pre > 0 && students[pre]->getId() > students[current]->getId()) {
        // This pause will NOT run:
        system("pause");
        temp = students[current];
        students[current] = students[pre];
        students[pre] = temp;
        pre--;
        current--;
    }
}

Student类的代码:

class Student : public Person {
private:
    int id;
    /* Other variables */
public:

    /* Constructors and functions */

    int getId() {
        return id;
    }
};

这到底是怎么回事?

【问题讨论】:

  • '这到底是怎么回事?'您很可能正在取消引用无效的 (NULL) 指针。
  • 也许内置调试器会有所帮助?比如可能告诉你哪一行产生了错误?
  • 我只有在使用调试器时才会得到错误,否则它只会崩溃。调试器说错误出现在从 getId 函数返回 id 的那一行。

标签: c++ visual-c++ visual-studio-2012


【解决方案1】:

根据提供的信息最可能的原因:

current 等于 nr_of_students,并且在

 while (pre > 0 && students[pre]->getId() > students[current]->getId())

current 用作数组索引。由于数组索引从zero 开始,如果nr_of_students 实际上等于数组中的元素数,这将是一个问题。例如。如果有5 元素,则最大索引可以是4,而不是5。如果使用5,内存位置无效,会返回无效的Student*,用这个无效的指针调用getId()会导致访问冲突错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2014-10-26
    • 2020-12-31
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多