为什么在 C++ 中使用 std 的 qsort() 函数时出现 0xC0000374 (STATUS_HEAP_CORRUPTION) 错误,如何修复它?

Cod*_*r88 1 c++ qsort heap-corruption

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Sam*_*hik 7

qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);
Run Code Online (Sandbox Code Playgroud)

qsort是一个C 库函数,它对C++ 类一无所知。就像结构中的对象一样,std::string这段代码试图排序。随之而来的是不明确的行为和欢闹。

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

#include <algorithm>

// ...

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