简体   繁体   English

为什么在使用 qsort() 函数时会出现 munmap_chunk(): invalid pointer Aborted?

[英]Why do I get munmap_chunk(): invalid pointer Aborted when using qsort() function?

I got this error "munmap_chunk(): invalid pointer Aborted" when I using qsort() to sort a array that contains class objects.当我使用 qsort() 对包含类对象的数组进行排序时,我收到此错误“munmap_chunk(): invalid pointer Aborted”。 Here is my code:这是我的代码:

#include <iostream>
#include <string>
#include <cstdlib>

class MyString : public string
{
 public:
    MyString(const char *str) :string(str) {}
    MyString(const string & str) :string(str) {}
};

int CompareString(const void * e1, const void * e2)
{
    MyString * s1 = (MyString *) e1;
    MyString * s2 = (MyString *) e2;
    if ( *s1 < *s2 ) return -1;
    else if ( *s1 == *s2 ) return 0;
    else if ( *s1 > *s2 ) return 1; 
}

int main()
{
    MyString SArray[4] = {"big","me","about","take"};
    qsort(SArray,4,sizeof(MyString), CompareString);
    for( int i = 0;i < 4;++i )
        cout << SArray[i] << endl;
    return 0;
}

When I comment out the qsort() line.当我注释掉 qsort() 行时。 The error disappears.错误消失。 I want to know why this happened and how to solve the error.我想知道为什么会发生这种情况以及如何解决错误。

My output:我的输出:

me

abo阿波

bi

take

munmap_chunk(): invalid pointer munmap_chunk(): 无效指针

Aborted中止

qsort works by copying elements around, but it does so by calling memcpy . qsort通过复制元素来工作,但它是通过调用memcpy This is undefined behaviour for non-POD types (such as std::string ), hence your crash.这是非 POD 类型(例如std::string )的未定义行为,因此您会崩溃。

Solution: use std::sort instead, which is the C++ way of sorting things.解决方案:改用std::sort ,这是 C++ 的排序方式。

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

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