C++ C++;Valgrind内存泄漏
Valgrind告诉我:C++ C++;Valgrind内存泄漏,c++,memory-leaks,new-operator,valgrind,C++,Memory Leaks,New Operator,Valgrind,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==
==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
有几个新的语句。我如何知道哪一个是导致泄漏的原因(即管线)
谢谢
附言:我很乐意发布代码,但代码太长了:/将-g
选项传递到gcc
或g++
,这样您的可执行文件中就有调试符号。下面是使用-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
通过这种方式,您可以看到进行分配的行。简单、长期的解决方案是将使用new
创建的数组更改为向量,将使用new
创建的任何其他指针分配内存更改为智能指针。内存将自动释放。@chris,我没有创建任何数组。请确保您有一个析构函数,在该析构函数中,在堆上的构造函数中创建的所有实例都将被释放并在最后释放。然后只使用智能指针,但请记住std::vector
,以备将来使用。它在各个方面都优于新的ed阵列。C++11提供了std::unique乇ptr
和std::shared乇ptr
,这会让您过得很好。您几乎不需要经常使用std::weak_ptr
。对于C++03,仍然有好的旧auto_ptr
,在上述三个版本的上下文中被弃用。@l19是在同一版本中编译和链接的Loader
类的源文件吗?真奇怪。您能否创建一个简单的程序(总是泄漏内存),并查看valgrind是否能够在您的环境中报告这方面的准确行?