读书人

关于delete自定义类型数组的有关问题

发布时间: 2012-02-05 12:07:15 作者: rapoo

关于delete自定义类型数组的问题
我编写了一个多项式的类,有一个函数用于求多项式的幂,其中动态申请了一个CComplex类的数组temp,用来存放多项式系数的临时值,但在执行函数结束时的delete [] temp时出现错误,说内存非法访问。但是,当多项式的次数order(与CPoly类中的CComplex a 数组的大小有关)为2次时,可以正常撤销temp数组,当次数order大于等于3时就会出现错误,2次与3次应该没有本质区别。程序的流程应该正确,不存在数组越界访问的情况,出错之后VC6.0直接跳到CComplex的析构函数中,此析构函数为空。

不知错误原因与析构函数是否有关,不知道为什么会出现循环次数不同时,程序运行情况不同的状况,请高手指点!!!

最后补一句:为什么这个贴子我只能给10分???我觉得这个问题有点复杂,我本想高分悬赏的,谁能告诉我为什么不能给高分啊?请大虾们见谅!!!

void CPoly::PolyPower(CPoly &b, int n)
{
......

if(b.a!=NULL)
delete [] b.a;
b.order = order*n;

b.a = new CComplex[order+1];

int i,j,k;
CComplex *temp = new CComplex[b.order+1];
for(i=0; i <b.order+1;i++)
{
temp[i].Initialize(0.0,0.0);
}

b.a[0].Initialize(1.0,0.0);

for(i=0; i <n; i++)
{
for(j=0; j <order+1; j++)
{
for(k=0; k <i*order+1; k++)
temp[k+j] = temp[k+j] + b.a[k]*a[j];
}
for(k=0; k <(i+1)*order+1; k++)
{
b.a[k]=temp[k];
temp[k].Initialize(0.0,0.0);
}
}
delete [] temp;
return;
}

class CPoly
{
public:
......
CPoly(const CPoly &b);
CPoly &operator=(const CPoly &a);
void PolyPower(CPoly &b, int n);
void Initialize(const CComplex b[], UINT n);

CPoly();
virtual ~CPoly();

UINT order;
CComplex *a;
};

class CComplex
{
public:
......
void Initialize(double a, double b);
double real();
double imag();
CComplex &operator =(const CComplex &a);
CComplex(CComplex &b);
CComplex();
virtual ~CComplex();

double imagpart;
double realpart;
};

[解决办法]
void CPoly::PolyPower(CPoly &b, int n)
里:
b.a = new CComplex[order+1];

而下面的循环里显然对b.a的使用是越界的
for(i=0; i <n; i++)
{
for(j=0; j <order+1; j++)
{
for(k=0; k <i*order+1; k++)
temp[k+j] = temp[k+j] + b.a[k]*a[j];
}
for(k=0; k <(i+1)*order+1; k++)
{
b.a[k]=temp[k];
temp[k].Initialize(0.0,0.0);
}
}

[解决办法]
就是数组越界!!!!!!!!!!

/////////////
b.order = order*n; !!!! (1)

b.a = new CComplex[order+1]; !! (2) order OR b.order?

CComplex *temp = new CComplex[b.order+1];
for(i=0; i <b.order+1;i++)
{
temp[i].Initialize(0.0,0.0);
}

b.a[0].Initialize(1.0,0.0);

for(i=0; i <n; i++)
{
for(j=0; j <order+1; j++)
{
for(k=0; k <i*order+1; k++)
temp[k+j] = temp[k+j] + b.a[k]*a[j]; !!! k=n*order+1, b.a[k]可能越界, 请看(2)

}
for(k=0; k <(i+1)*order+1; k++)
{
b.a[k]=temp[k]; !!! k=n*order+1, b.a[k]可能越界, 请看(2)
temp[k].Initialize(0.0,0.0);
}

读书人网 >C++

热点推荐