我正在实现我的类以使用矩阵,但在其中一种类方法中,在分析代码时,Visual Studio 报告缓冲区溢出。
编码:
typedef unsigned int UINT;
class NumCxx
{
//some implementation
};
UINT NumCxx::ones(UINT columns, UINT rows) // Method ones creates the matrix;
// UINT - unsigned int
{
if (!checkout())
{
this->dim_array_ = new int* [columns_]; // Creates an array
}
this->columns_ = columns;
this->rows_ = rows;
this->length_ = columns_; // length of an array
for (UINT i = 0; i < columns_; ++i)
{
dim_array_[i] = new int[rows_]; // PROBLEM is here
for (UINT j = 0; j < rows_; ++j)
{
dim_array_[i][j] = 1;
}
}
return 0;
}
Visual Studio 突出显示dim_array_[i] = new int[rows_];
该行并显示缓冲区溢出。
该方法UINT NumCxx::checkout()
检查是否已创建矩阵,如果未创建,则字符串this->dim_array_ = new int* [columns_];
创建二维动态数组。
结帐()代码:
UINT NumCxx::checkout()
{
if (length_) // Если длина была задана (по умолчанию в конструкторе = 0)
{
for (UINT i = 0; i < length_; ++i)
{
delete[] dim_array_[i];
}
return 1;
}
return 0;
}
如何消除这个不愉快的时刻,或者只是忽略它(我不想)?
length_
当您同时拥有行数和列数时,绝对不清楚为什么需要成员 。checkout
length_ != 0
。然后checkout
由函数释放内存,按数量length_
(不清楚多少),然后将值ones
分配给函数中的指针(但现在是不同数量的指针)。也许你还想要
this->dim_array_ = new int* [rows_] и dim_array_[i] = new int[columns_];
??PS 相反
length_
(在我看来,这个字段更困扰你)只是使用columns_