Linux下通过valgrind定位程序内存问题

本文介绍了如何在Linux环境下使用valgrind工具来定位和分析程序的内存问题,包括内存泄露、重复释放和错误释放。通过示例代码展示valgrind的使用过程,并分析了不同类型的内存问题可能导致的后果。
摘要由CSDN通过智能技术生成

目录

内存泄露

重复释放

错误释放

相关资料


内存泄露

示例代码

// MemoryLeak.cpp : 定义控制台应用程序的入口点。
//

#include <stdlib.h>
#include <string>

char* AllocateMemory(size_t nSize)
{
	return new char[nSize];
}

int main()
{
	size_t nSize = 16;
	char* pszData = AllocateMemory(nSize);
	
	// do something	

	return 0;
}

编译:g++ -Wall -g  MemoryLeak.cpp -o MemoryLeak

执行:valgrind --log-file=MemoryLeak.log --tool=memcheck --leak-check=full -v  ./MemoryLeak

MemoryLeak.log内容如下:

==14736== Memcheck, a memory error detector

==14736== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.

==14736== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info

==14736== Command: ./MemoryLeak

==14736== Parent PID: 3836

==14736==

==14736==

==14736== HEAP SUMMARY:

==14736==     in use at exit: 16 bytes in 1 blocks

==14736==   total heap usage: 2 allocs, 1 frees, 72,720 bytes allocated

==14736==

==14736== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1

==14736==    at 0x4C3089F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==14736==    by 0x108691: AllocateMemory(unsigned long) (MemoryLeak.cpp:9)

==14736==    by 0x1086AF: main (MemoryLeak.cpp:15)

==14736==

==14736== LEAK SUMMARY:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值