我是一個Java程序員,但現在我必須寫的代碼一點點C++。幾年前,我學習了C++的基礎知識,所以我不太適合。C++的malloc錯誤
我寫它描述了多項式有點類。那就是:
#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),然後給係數,程序不打印polynome並返回以下錯誤:
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,但是那裏提到的解決方案對我沒有多大幫助。
也許你可以看到在我的代碼的另一個問題?我將衷心感謝您的幫助。
在此先感謝。
你能張貼的頭文件? – 2011-05-09 10:33:31
你應該做'刪除在析構函數[] coeff';或者更好的是,使用'的std ::矢量'(這將擺脫你的'degree'成員,也是如此)。 –
2011-05-09 10:40:34
另外,刪除poly; – 2011-05-09 10:45:00