簡體   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