【问题标题】:C++ Valgrind memory leakC++ Valgrind 内存泄漏
【发布时间】:2012-09-25 03:12:51
【问题描述】:

Valgrind 告诉我:

==19305== 16 bytes in 1 blocks are definitely lost in loss record 19 of 179
==19305==    at 0x402842F: operator new(unsigned int)
==19305==    by 0x805273E: Loader::createLevel(int, int, std::string, Player*, int, int, int) 
==19305==    by 0x80551B0: Loader::loadLevel()
==19305==    by 0x80676C2: main (main.cpp:38)

我的函数Loader:.createLevel 有几个new 语句。我怎么知道是哪一个导致了泄漏(即线路)?

谢谢!

P.S.:我很乐意发布代码,但它太长了:/

【问题讨论】:

  • 简单的长期解决方案是将使用new 生成的数组更改为向量,并将使用new 分配的任何其他指针内存更改为智能指针。内存将被自动释放。
  • @chris,我没有创建任何数组
  • 确保你有一个析构函数,在这个析构函数中,在堆上的构造函数中创建的所有实例都在最后被释放和释放。
  • 那么只是智能指针,但请记住 std::vector 以备将来使用。它在各个方面都优于newed 数组。 C++11 提供了std::unique_ptrstd::shared_ptr,它们会让你很顺利。您几乎不需要std::weak_ptr。对于 C++03,仍然有旧的 auto_ptr 在上述三个上下文中被弃用。

标签: c++ memory-leaks new-operator valgrind


【解决方案1】:

-g 选项传递给gccg++,以便您的可执行文件中包含调试符号。这是使用 -g 在二进制文件上运行 valgrind 的示例。

==20538== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==20538==    at 0x4A05809: malloc (vg_replace_malloc.c:149)
==20538==    by 0x4004F7: main (test.c:8)
==20538==
==20538== LEAK SUMMARY:
==20538==    definitely lost: 4 bytes in 1 blocks.
==20538==      possibly lost: 0 bytes in 0 blocks.
==20538==    still reachable: 0 bytes in 0 blocks.
==20538==         suppressed: 0 bytes in 0 blocks.
==20538== Reachable blocks (those to which a pointer was found) are not shown.
==20538== To see them, rerun with: --show-reachable=yes

gcc -g test.c

这样您就可以看到进行分配的行。

【讨论】:

  • @l19 Loader 类的源文件是否在同一个版本中编译和链接?那很奇怪。您能否创建一个简单的程序(总是泄漏内存)并查看 valgrind 是否可以在您的环境中为此报告确切的行#?
猜你喜欢
  • 2020-03-31
  • 2016-03-15
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2013-06-24
  • 2019-07-02
  • 2021-11-28
  • 2020-06-23
相关资源
最近更新 更多