繁体   English   中英

为什么在 C++ 中使用 std 的 qsort() function 时出现 0xC0000374 (STATUS_HEAP_CORRUPTION) 错误,我该如何解决?

[英]Why do I get 0xC0000374 (STATUS_HEAP_CORRUPTION) error when using qsort() function of std in C++, and how do I fix it?

这是一个简单的 C++ 测试代码,它只会按学生的结构对学生结构进行排序,学生 ID 是 integer:

#include <iostream>

using namespace std;

struct student {
    int grade;
    int studentId;
    string name;
};

int studentIdCompareFunc(const void * student1, const void * student2);


int main()
{
    const int ARRAY_SIZE = 10;
    student studentArray[ARRAY_SIZE] = {
        {81, 10009, "Aretha"},
        {70, 10008, "Candy"},
        {68, 10010, "Veronica"},
        {78, 10004, "Sasha"},
        {75, 10007, "Leslie"},
        {100, 10003, "Alistair"},
        {98, 10006, "Belinda"},
        {84, 10005, "Erin"},
        {28, 10002, "Tom"},
        {87, 10001, "Fred"},
    };

    qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);

    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        cout << studentArray[i].studentId << " ";
    }

}


int studentIdCompareFunc(const void * voidA, const void * voidB)
{
    student* st1 = (student *) (voidA);
    student* st2 = (student *) (voidB);
    return st1->studentId - st2->studentId;
}

它按预期打印 studentId 整数,但不返回零,它返回 -1072740940 (0xC0000374)。

我通过将 ARRAY_SIZE 更改为 15 或增加 ARRAY_SIZE 参数进行了测试,但我仍然得到相同的结果。

这个错误的原因是什么? 我如何解决它?

qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);

qsort是一个C 库 function ,它对 C++ 类一无所知 就像这段代码试图排序的结构中的std::string object 一样。 随之而来的是不确定的行为和多变现象。

如果此处的意图是编写 C++ 代码,则使用 C++ 等效项std::sort ,它是本机 C++ 算法:

#include <algorithm>

// ...

std::sort(studentArray, studentArray+ARRAY_SIZE,
   []
   (const auto &a, const auto &b)
   {
       return a.studentId < b.studentId;
   });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM