C++ heap corruption detected occurs while I try to use the function I made in derived class -
here comes code. firstly have defined 3 class
class matrix {protected: double *mdata; int rows,columns;
class polyg{protected: matrix x,y,z,centre;
class triangle: public polyg{protected:public: triangle(matrix x1,matrix y1,matrix z1){x=x1;y=y1;z=z1; centre=(x+y+z).change_scale(1/3); }
and have defined overloading function matrix multiplication such
matrix operator*(matrix &m) const{ if(columns!=m.getrows()) { cout<<"invalid size!!"<<endl; exit(1); } matrix temp(rows,m.getcols()); for(int x=0; x<rows; x++) { for(int y=0; y<m.getcols(); y++) { double value = 0; for(int z=0; z<columns; z++) { value = value+(mdata[index(x+1,z+1)]*m.mdata[index(z+1,y+1)]); } temp.mdata[index(x+1,y+1)] = value; } } return temp;}
index function defined as
int index(int m, int n) const // return position in array of element (m,n){ if(m>0 && m<=rows && n>0 && n<=columns) return (n-1)+(m-1)*columns; else {cout<<"error: out of range"<<endl; exit(1);}
}
and defined member function, overrides pure virtual function in polyg class, in triangle class such as
void rotate(double angle){ double pi=4*atan(1.0); double angle_rad=pi*angle/180; matrix m_rot(2,2); m_rot(1,1)=cos(angle_rad); m_rot(1,2)=sin(angle_rad); m_rot(2,2)=cos(angle_rad); m_rot(2,1)=-sin(angle_rad);//matrix of rotation of angle inserted x=m_rot*x; y=m_rot*y; z=m_rot*z;//rotating triangle }
problem occurs from
x=m_rot*x; y=m_rot*y; z=m_rot*z;
this part. heap corruption detected error occurs part. if remove part, code runs totally without problem.
also, if define in main
int main(){matrix a,b,c; c=a*b;
it works totally also.
however if use function made in triangle class,for example,
triangle tri(a,b,c); tri.rotate(30);
problem occurs
no errors occur before debugging after compile, heap corruption detected error occurs
could explain problem? , how fix it?
this code looks suspect me:
for(int x=0; x<rows; x++) { for(int y=0; y<m.getcols(); y++) { double value = 0; for(int z=0; z<columns; z++) { value = value+(mdata[index(x+1,z+1)]*m.mdata[index(z+1,y+1)]); } temp.mdata[index(x+1,y+1)] = value;
with z
iterating on column indexes, pass value first argument index
function (source no longer present in post) appears assume first argument row index.
Comments
Post a Comment