【发布时间】:2021-11-29 07:04:38
【问题描述】:
我尝试学习 CPP 指针以及释放我使用过的所有内存 valgrind。但不幸的是,我遇到了泄漏错误,我不知道我在哪里犯了错误。也没有太多关于从 valgrind 中找到错误的想法,而是一种人类可读的方式。任何发现泄漏的指导都是非常可观的。
编译器: g++ (Ubuntu 7.5.0-3ubuntu1~16.04) 7.5.0
sn-p相关信息
-
smart pointer不是故意使用的 - 这是一个最小的示例代码。所以,有些部分似乎是不必要的。
file.cpp
#include <iostream>
void algo_fun(unsigned int* ip_ptr_array_,
unsigned int ip_size_,
unsigned int** op_ptr_array_,
unsigned int* op_size_)
{
*(op_size_) = ip_size_ + 2;
// following approach is good as it allocate dynamic memory
unsigned int* local = new unsigned int[*(op_size_)];
for (unsigned int i = 0; i< *(op_size_); i++)
{
local[i]=i+1*3;
}
*op_ptr_array_ = &local[0];
local[3] = 87;
}
int main()
{
// input array's contetnt
unsigned int ip_size = 10;
unsigned int* ip_ptr_array = new unsigned int[ip_size];
// output data
unsigned int op_size;
unsigned int* op_ptr_array;
// filling input array
for(unsigned int i = 0; i < ip_size; i++)
{
ip_ptr_array[i] = i+2*2;
}
// function calling to get output data
algo_fun(ip_ptr_array,
ip_size,
&op_ptr_array,
&op_size);
delete [] ip_ptr_array;
delete [] op_ptr_array;
return 0;
}
可以在here找到工作版本。
用于测试的命令: valgrind --leak-check=full --show-leak-kinds=all -v ./file
Leak Summary from valgrind
==23138== LEAK SUMMARY:
==23138== definitely lost: 0 bytes in 0 blocks
==23138== indirectly lost: 0 bytes in 0 blocks
==23138== possibly lost: 0 bytes in 0 blocks
==23138== still reachable: 72,704 bytes in 1 blocks
==23138== suppressed: 0 bytes in 0 blocks
==23138==
==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
【问题讨论】:
-
您为什么要手动使用
new和delete?这就是 C++ 中容器和智能指针的用途。 -
无法重现,valgrid 打印“所有堆块都已释放——不可能有泄漏”。
-
algo_fun(ip_ptr_array, ip_size,&op_ptr_array,&op_size);-- 最后一个参数不需要是指针。它应该只是一个普通的int。如果您查看algo_fun函数,它绝对不会暗示它应该是一个指针——例如,在该函数中没有进行nullptr检查。看起来你对代码中的所有内容都进行了指针化。 -
@PaulMcKenzie 据我了解,
ip_表示输入参数,op_表示输出参数。algo_fun()将输出数组的元素个数存储到op_size_指针指向的位置,参见:*(op_size_) = ip_size_ + 2;因此,它需要是一个指针。至于指针化一切,我认为作者只是在学习/练习他们关于 C++ 指针的知识。否则,根本不需要在任何地方使用指针,只需std::vectors 和引用。我认为这段代码只是一个概念证明。例如,ip_ptr_array_参数未使用。 -
@πάνταῥεῖ 故意避开
smart pointer。
标签: c++ pointers memory-leaks valgrind