首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在STATUS_HEAP_CORRUPTION中使用std的qsort()函数时会出现0xC0000374 ( C++ )错误,以及如何修复?

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

Stack Overflow用户
提问于 2022-08-18 21:48:09
回答 1查看 153关注 0票数 1

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

代码语言:javascript
复制
#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参数进行了测试,但仍然得到了相同的结果。

造成这个错误的原因是什么?我该怎么解决呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-18 21:57:57

代码语言:javascript
复制
qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);

qsort是一个C库函数,它对C++类完全不了解。就像结构中的std::string对象一样,这段代码试图排序。不明确的行为,和乡下人,接踵而来。

如果这里的目的是编写C++代码,那么使用C++等效的std::sort,这是一个原生C++算法:

代码语言:javascript
复制
#include <algorithm>

// ...

std::sort(studentArray, studentArray+ARRAY_SIZE,
   []
   (const auto &a, const auto &b)
   {
       return a.studentId < b.studentId;
   });
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73409797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档