3D 阵列中的瓦尔格林德错误C++
Valgrind error in C++ 3D array
我在编译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
或简单地使用单维数组并自己实现行,列和深度。
您的指数计算错误。
z
从0
到depth
.j
从0
到height
.k
从0
到width
.到目前为止一切顺利(好吧,j
和k
而不是x
和y
是不寻常的,可能是混乱的很大一部分(。但:
_3D_matrix[j * height * depth + k * depth + z] = value;
将j
乘以height
是错误的,可能应该是width
.
考虑这种情况:j = height - 1
、k = 0
、z = 0
。那么你的索引将是height * depth * (height - 1)
的,如果height
与width
不同,这显然是不正确的。
调试不确定数组索引的情况的一个技巧是考虑极端情况。如果您考虑上述情况(或所有循环变量都是最大值的情况(,您将立即看到索引可以超过数组大小。
相关文章:
- 删除堆后对瓦尔格林德错误感到困惑
- 瓦尔格林德报告在 =带有嵌套shared_ptrs的运算符上的读取错误
- 瓦尔格林德错误 - 地址0x0不是堆叠的 malloc'd 或自由的
- 瓦尔格林德错误来自 boost::asio
- 修复了瓦尔格林德错误内存泄漏的错误
- 3D 阵列中的瓦尔格林德错误C++
- 访问字符串::c_str()的结果时出现瓦尔格林德内存访问错误
- 段错误,但不是在瓦尔格林德或GDB中
- 我应该如何修复瓦尔格林德的未初始化值错误?
- 二叉搜索树瓦尔格林德错误"Invalid read of size 8"
- C++赋值构造函数瓦尔格林德错误
- 为什么我会遇到分段错误?瓦尔格林德
- 瓦尔格林德无效读取大小 4 错误
- C++内存泄漏检查中的瓦尔格林德错误
- 有人可以用打开的 mpi 解释这个瓦尔格林德错误吗?
- 瓦尔格林德错误"Invalid read of size 4"
- 为什么瓦尔格林德会给出"Invalid read of size 1"错误?
- C++瓦尔格林德错误
- 瓦尔格林德 - 错误
- 瓦尔格林德错误,未初始化的值