我的数组值是如何被覆盖的

How are my array values getting overwritten

本文关键字:覆盖 数组 我的      更新时间:2023-10-16

我正在创建一个int数组和一个重载((运算符的类的实例。这是课程:

模板CMatrix类{公用:

CMatrix(const int d);
CMatrix(const int d1, const int d2);
CMatrix(const CMatrix<M> &old); // copy ctor
~CMatrix();
int getXSize() {return s1;}
int getYSize() {return s2;}
CMatrix<M>& operator=(const CMatrix<M> &cm);// Asgnmnt constructor
CMatrix<M>& operator*(CMatrix<M> &cm);
inline M& operator()(const int i) {
    ASSERT1(i<s1 && i>=0);
    printf("CMatrix::operator(): i=%d, s1=%dn", i, this->s1);
    return m[i];
}
inline M& operator()(const int i, const int j) {
    ASSERT2(i<s1 && j<s2);
    ASSERT2(i>=0 && j>=0);
    return m[i*s2+j];
}
int s1, s2; // dimensions of array
M *m;   // pointer to first element of matrix.
int dimensions;

声明:

int *oldRow=NULL;
CMatrix<int> *useRow=NULL;

以下是它们的定义:

oldRow = new int(nNodes);
useRow = new CMatrix<int>(nNodes);

我有一个循环来初始化它们:

printf(": &oldRow[0]=%un", oldRow);
printf(": &oldRow[7]=%un", &oldRow[7]);
printf(": &(useRow->s1)=%un", &(useRow->s1));
printf(": &(useRow->m)=%un", &(useRow->m));
for (int i=0; i<nNodes; i++) {
   *(oldRow+i)=99;
   printf("A: s1=%dn",(*useRow).s1);
   printf("B: i=%dn", i);
   (*useRow)(i)=0;
   printf("C: i=%dn", i);
   for (int j=0; j<nNodes; j++) nonZeroCount(i,j)=0;
}

最后,这里是输出。看看s1被覆盖:

: &oldRow[0]=39846784
: &oldRow[7]=39846812
: &(useRow->s1)=39846800
: &(useRow->m)=39846808
A: s1=8
B: i=0
CMatrix::operator(): i=0, s1=8
C: i=0
A: s1=8
B: i=1
CMatrix::operator(): i=1, s1=8
C: i=1
A: s1=8
B: i=2
CMatrix::operator(): i=2, s1=8
C: i=2
A: s1=8
B: i=3
CMatrix::operator(): i=3, s1=8
C: i=3
A: s1=99
B: i=4
CMatrix::operator(): i=4, s1=99

我知道这有点复杂;我试着让它尽可能简单,但仍然保留了所有相关的细节。我在useRow中使用了第二个普通的旧int数组,但我遇到了随机崩溃,所以我想我应该使用我的CMatrix类。

无论如何,请注意输出顶部的地址-useRow->s1和useRow->m都位于oldRow数组的中间!

我知道我一定做错了什么,但我不知道是什么。我也为它们使用了std::class,但它们也会随机崩溃,我认为int*oldRow可能不太容易出错。。。

oldRow = new int(nNodes);

由此,我怀疑oldRow的类型是指向int的指针。上面的那行将指针设置为指向单个整数,并初始化为nNodes的值。

你的意思可能是

oldRow = new int[nNodes]{};
//              ^      ^  
//               array   C++11 default init of the elements

事实上,当您稍后访问oldRow的"元素"时,您调用的是未定义的行为:通过在一个元素"数组"的边界之外写入,您覆盖了堆中的其他内容,损坏了堆并修改了其他分配的数据(在这种情况下,如果是您的类,则是该实例的成员字段(。

我也为它们使用了std::class,但它们也会发生随机崩溃,我认为int*oldRow可能不太容易出错。。。

一般来说,除非真的需要,否则不应该使用如上所述的原始分配数组。std::vector类为运行时大小的数组提供了更好的方法。如果它随机崩溃,那么这是你做错了什么的直接迹象。