3D 阵列中的瓦尔格林德错误C++

Valgrind error in C++ 3D array

本文关键字:林德 错误 C++ 阵列 3D      更新时间:2023-10-16

我在编译C++程序以创建和管理 3D 数组时无法理解显示的 Valgrind 错误。

我在Mac上编写了软件,一切看起来都很好,但是当我将其移植到Ubuntu时,不仅出现Valgrind错误,而且输出也与Mac中的输出不同(并且错误(。

这是瓦尔格林德错误:

==10705== Invalid write of size 4
==10705==    at 0x401095: Matrice3D<int>::Matrice3D(unsigned int, unsigned int, unsigned int, int const&) (in /media/psf/sharedFolder/Progetto_2/main.exe)
==10705==    by 0x400BE1: main (in /media/psf/sharedFolder/Progetto_2/main.exe)
==10705==  Address 0x5ab6e10 is 0 bytes after a block of size 192 alloc'd
==10705==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10705==    by 0x40102E: Matrice3D<int>::Matrice3D(unsigned int, unsigned int, unsigned int, int const&) (in /media/psf/sharedFolder/Progetto_2/main.exe)
==10705==    by 0x400BE1: main (in /media/psf/sharedFolder/Progetto_2/main.exe)
==10705== 
--10705-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting
--10705-- si_code=1;  Faulting address: 0x1105AB6E38;  sp: 0x802ca9e30

构造函数引用:

Matrice3D(unsigned int height, unsigned int width, unsigned int depth, const T &value) : _3D_matrix(0), _height(0), _width(0), _depth(0) { 
try {
_3D_matrix = new T[height * width * depth];
for (int z = 0; z < depth; z++) {
for (int j = 0; j < height; j++) {
for (int k = 0; k < width; k++) {
_3D_matrix[j * height * depth + k * depth + z] = value; 
}
}
}
}
catch(...) {
delete[] _3D_matrix;
throw;
}

_height = height;
_width = width;
_depth = depth;
}

有人有过类似的经历吗?我做错了什么吗? 提前感谢!

看起来写入问题是由混合各种for级别的范围/索引引起的:

_3D_matrix[j * height * depth + k * depth + z] = value;

看看这里:https://ideone.com/gkUXib - 你的代码移动到一个独立的函数中,并添加了索引输出。输出显示一些索引被分配给两次(即示例中的 22(,一些索引从未分配给(如 63(。索引的顺序看起来很奇怪,很难推理。

宽度,高度和深度的某种组合可能会导致您注意到的错误。

我建议简化fors变量(使"行"表示行,而不是其他东西(,使用std::array或简单地使用单维数组并自己实现行,列和深度。

您的指数计算错误。

z0depth.
j0height.
k0width

.到目前为止一切顺利(好吧,jk而不是xy是不寻常的,可能是混乱的很大一部分(。但:

_3D_matrix[j * height * depth + k * depth + z] = value;

j乘以height是错误的,可能应该是width.
考虑这种情况:j = height - 1k = 0z = 0。那么你的索引将是height * depth * (height - 1)的,如果heightwidth不同,这显然是不正确的。

调试不确定数组索引的情况的一个技巧是考虑极端情况。如果您考虑上述情况(或所有循环变量都是最大值的情况(,您将立即看到索引可以超过数组大小。