当我试图使用我在派生类中创建的函数时,检测到的c++堆损坏发生

C++ heap corruption detected occurs while I try to use the function I made in derived class

本文关键字:检测 损坏 函数 c++ 创建 派生      更新时间:2023-10-16

我的代码来了。首先,我定义了三个类

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); }

和我为矩阵乘法定义了一个重载函数,如

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;}

索引函数定义为

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);}

}

和我定义了成员函数,它覆盖了多边形类中的纯虚函数,在三角形类中,如

    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 the triangle
}

问题发生于

x=m_rot*x;
y=m_rot*y;
z=m_rot*z;

这部分。此部分发生堆损坏检测错误。如果我删除这部分,代码完全运行良好,没有任何问题。

同样,如果我在main

中定义
int main(){matrix a,b,c; c=a*b;

效果也很好。

但是如果我使用我在三角形类中创建的函数,例如,

triangle tri(a,b,c); tri.rotate(30);
问题发生在

调试前没有错误但在我编译之后,发生堆损坏检测错误

谁能解释一下是什么问题?如何解决这个问题?

我觉得这段代码很可疑:

 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;

使用z,您正在迭代列索引,但您将该值传递作为index函数的第一个参数(来源现在不再存在于您的帖子中),这似乎假设第一个参数始终是行索引。