C++ malloc错误

Dar*_*rie 1 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<<" + ";
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

好的,现在我试着读取多项式的度数和系数,并在控制台中打印出来.这是代码:

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

编译代码时,一切正常.在运行时,如果我给出一个偶数度然后给出一些系数,程序就会正常运行.但是:如果我定义一个奇数(例如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.
Run Code Online (Sandbox Code Playgroud)

为什么会这样?哪里没有为阵列分配足够的内存?我用Google搜索了这个错误并偶然发现了这个页面,但那里提到的解决方案对我帮助不大.

也许你可以在我的代码中看到另一个问题?我将衷心感谢您的帮助.

提前致谢.

小智 12

你的代码有很多错误.C++与Java完全不同,似乎你正在使用指针,就好像它们就像Java中的引用一样,它们实际上并非如此.

Polynom::Polynom()
{
    this->degree = 0;
    this->coeff = new int[0];
}
Run Code Online (Sandbox Code Playgroud)

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

Polynom::~Polynom()
{
    delete coeff;
}
Run Code Online (Sandbox Code Playgroud)

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

Polynom::~Polynom()
{
    delete [] coeff;
}
Run Code Online (Sandbox Code Playgroud)

这个:

void Polynom::setDegree(int degree)
{
    this->degree = degree;
}
Run Code Online (Sandbox Code Playgroud)

毫无意义 - 你改变了程度,但没有改变与之相关的数组.

void Polynom::setCoeffs(int* coeff)
{
    this->coeff = &*coeff;
}
Run Code Online (Sandbox Code Playgroud)

我不知道你认为这是做什么的,我怀疑你也不知道.你有内存泄漏.

那只是初学者 - Isuspect有更多不好的东西.你需要做两件事:

  • 阅读一本关于C++的书.由于您有编程经验,我建议使用Accelerated C++.

  • 忘掉你的Java知识吧.正如我所说,这两种语言几乎没有任何共同之处.