c++ - 为什么 valgrind 和 gdb 指向不同的代码行?或者:如何在循环中分配指针的 malloc() 和 free() 指针?
问题描述
以下代码中的循环可以执行几次,但随后会崩溃。
#include <cstdlib>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
//not needed but program will not crash if I remove it
int blocksize=stoi(argv[1]);
//typical value 70-100
int min_length=stoi(argv[2]);
for(int i=0;i<250000;i++)
{
//Allocate memory for new integer array[row][col]. First allocate the memory for the top-level array (rows).
int **output_std = (int**) malloc(20*sizeof(int*));
//Allocate a contiguous chunk of memory for the array data values.
output_std[0] = (int*) malloc( min_length*20*sizeof(int) );
//Set the pointers in the top-level (row) array to the correct memory locations in the data value chunk.
for (int k=1; k < 20; k++)
{
output_std[k] = output_std[0]+k*min_length;
}
//do something with output_std
//free malloc'd space
free(output_std[0]);
for(int k=0;k<20;k++)
{
output_std[i]=NULL;
}
free(output_std);
output_std=NULL;
}
return 0;
}
GDB
使用指向第 36 行的点进行调试: free(output_std);
. 调试valgrind
产生以下错误:
nvalid write of size 8
==32161== at 0x4031A0: main (test.cpp:31)
==32161== Address 0x82f2620 is 0 bytes after a block of size 160 alloc'd
==32161== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==32161== by 0x403159: main (test.cpp:16)
第 16 行是:int **output_std = (int**) malloc(20*sizeof(int*));
第 31 行是:free(output_std[0]);
为什么我的代码中的错误位置不同?
在这种情况下如何进行?
(如何修复我的代码?)
编辑:线条是正确的。我需要这样一个第三方库的对象。
解决方案
Valgrind 通常可以更早地发现问题。这就是使用它的意义所在。Valgrind 经常抓住问题的根源(或者更接近根源),而在 GDB 中你只能看到后果。
在您的情况下,问题的根源是由越界写入数组引起的堆内存损坏。结果是free
由该堆损坏引起的内部崩溃。Valgrind 抓住了前者。当你运行你的程序时(例如在 GDB 下)你只能看到后者。
在您的代码中
for(int k=0;k<20;k++)
{
output_std[i]=NULL;
}
预期的迭代变量是k
. 但是您正在访问您的数组i
。此时i
显然是20
,这会导致 valgrind 捕获越界访问。
我想说这个循环无论如何都是毫无意义的:你试图将你即将释放的内存归零。人们可以提供一些关于为什么它可能有意义的论据......但是在调试版本的库中,在内存释放函数本身内部,这样的事情更合适。在用户级代码中,它只会用不必要的噪音使代码混乱。
PS无论如何,您显然发布了无效的行号。如果free(output_std)
是第 36 行,那么 valgrind 应该将违规行视为 34,而不是 31。请下次发布准确的代码并努力准确识别违规行。
推荐阅读
- regex - 无效表达式:图像中的正则表达式标志 p 无效
- macos - 如何在 MacOS 上只安装 Docker 客户端?
- javascript - 为什么谷歌地图在网站上不起作用?
- regex - 正则表达式 + vee 验证
- ios - 在 UITableView 单元格上快速求和值
- angular - 如何获取兄弟元素的属性
- html - 如何从角度6中的数组中获取上一个最接近的数字
- forms - 带有 EntityType 下拉值的引导标签输入 (Symfony)
- assembly - 一个地址有多少字节?
- asynchronous - How to asynchronously explore a directory and its sub-directories?