C++ malloc 错误

标签 c++ malloc

我是一名 Java 程序员,但现在我必须用 C++ 编写一些代码。我几年前学习了 C++ 的基础知识,所以我不太适合。

我写了一个描述多项式的小类。在这里:

#include "Polynom.h"
#include <iostream>

using namespace std;

Polynom::Polynom()
{
    this->degree = 0;
    this->coeff = new int[0];
}

Polynom::Polynom(int degree)
{
    this->degree = degree;
    this->coeff = new int[degree + 1];
}

Polynom::~Polynom()
{
    delete coeff;
}

void Polynom::setDegree(int degree)
{
    this->degree = degree;
}

void Polynom::setCoeffs(int* coeff)
{
    this->coeff = &*coeff;
}

void Polynom::print()
{
    int i;
    for(i = degree; i >= 0; i --)
    {
        cout<<this->coeff[i];
        if(i != 0)
            cout<<"x^"<<i;
        if(i > 0)
        {
            if(coeff[i - 1] < 0)
                cout<<" - ";
            else
                cout<<" + ";
        }
    }    
}

好的,现在我尝试读取多项式的次数和系数并将其打印在控制台中。这是相关代码:

#include <iostream>
#include "Polynom.h"
using namespace std;

int main()
{
    int degree;

    cout<<"degree = ";
    cin>>degree;
    int* coeff = new int[degree];
    int i;
    for(i = 0; i <= degree; i++)
    {
        cout<<"coeff[x^"<<i<<"] = ";
        cin>>coeff[i];
    }
    Polynom *poly = new Polynom(degree);
    //poly->setDegree(degree);
    poly->setCoeffs(coeff);
    cout<<"The input polynome is: ";
    poly->print();
    return 0;
}

编译代码时,一切正常。运行时,如果我给一个度,然后给一些系数,程序运行正常。 但是:如果我定义一个度(例如3或5)然后给出系数,程序不会打印多项式并返回以下错误:

malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.

为什么会这样?我在哪里没有为数组分配足够的内存?我在谷歌上搜索了这个错误并偶然发现了 this page ,但是那里提到的解决方案对我没有太大帮助。

也许您可以在我的代码中看到另一个问题?非常感谢您的帮助。

提前致谢。

最佳答案

您的代码存在大量错误。 C++ 与 Java 完全不同,您似乎在使用指针,就好像它们就像 Java 中的引用一样,但它们显然不是。

Polynom::Polynom()
{
    this->degree = 0;
    this->coeff = new int[0];
}

这将创建一个大小为零的数组,这在 C++ 中是合法的,但几乎不是您想要的。

Polynom::~Polynom()
{
    delete coeff;
}

C++ 中的数组必须用 delete[] 删除:

Polynom::~Polynom()
{
    delete [] coeff;
}

这个:

void Polynom::setDegree(int degree)
{
    this->degree = degree;
}

没有意义——你改变了度数,但没有改变它关联的数组。

void Polynom::setCoeffs(int* coeff)
{
    this->coeff = &*coeff;
}

我不知道你认为这是在做什么,我怀疑你也不知道。而且你有内存泄漏。

这只是初学者 - 我怀疑还有更多不好的东西。你需要做两件事:

  • 阅读一本关于 C++ 的书。因为你有编程经验,我推荐Accelerated C++ .

  • 忘记您的 Java 知识。正如我所说,这两种语言几乎没有任何共同点。

关于C++ malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5935576/

相关文章:

c++ - 推导容器和 initializer_list-s 的模板函数

c++ - 在堆栈内存中销毁的对象

c - 使用 void 在 C 中分配和释放二维数组

条件堆免费

c++ - 在命名空间中使用 constexpr double

c++ - 访问私有(private)成员导致段错误

c++ - gcc 6.1 可执行文件链接错误

c - 使用 realloc() 获得精确数量 vs malloc() 获得太多

c - 打印垃圾 [C]

c - 指针和动态内存