저는 Java 프로그래머입니다. 그러나 이제는 C++로 약간의 코드를 작성해야합니다. 2 년 전 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;
}
코드를 컴파일 할 때 모든 것이 정상입니다. 달릴 때 도조차 준 다음 몇 가지 계수를 주면 프로그램이 정상적으로 실행됩니다. 그러나 : I (예 : 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을 우연히 발견했지만, 거기에 언급 된 해결책은별로 도움이되지 못했다.
내 코드에서 다른 문제가 발생할 수 있습니까? 나는 정말로 당신의 도움에 감사 할 것입니다.
미리 감사드립니다. 당신의 main()
기능에
헤더 파일을 게시 할 수 있습니까? –
소멸자에서'delete [] coeff'를 수행해야합니다. 또는 더 나은 방법은'std :: vector'을 사용하는 것인데 (이것은'degree' 멤버를 제거 할 것이다). –
또한 삭제 폴리; –