当我试图使用我在派生类中创建的函数时,检测到的c++堆损坏发生
C++ heap corruption detected occurs while I try to use the function I made in derived 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);
}
和我为矩阵乘法定义了一个重载函数,如
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
函数的第一个参数(来源现在不再存在于您的帖子中),这似乎假设第一个参数始终是行索引。
相关文章:
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 删除字符串后C++检测到堆损坏
- 检测到堆损坏(字符串导致堆损坏)|C++
- 在C++中检测到堆损坏错误
- C++ 内存损坏检测
- 如何修复检测到堆损坏:正常阻止后
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 编译器如何检测内存损坏
- 排序程序的错误(检测到堆损坏)
- 正常块错误后检测到的堆损坏
- C++ 删除数组时检测到堆损坏
- 调试错误,在C++中检测到堆损坏
- 检测到堆损坏(类方法)
- 在普通块(#164)之后检测到堆损坏
- jemalloc未检测到内存损坏
- 检测到合并排序堆损坏
- 错误: *** 检测到 glibc *** w5:双重释放或损坏(快速顶部):
- 检测到堆损坏:在正常块(#62)之后
- 在Windows上立即检测到堆损坏错误.如何