一个查看堆内存泄露的工具

valgrind

复制代码
 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 
 4 void f(void)
 5 {
 6     int *x = malloc(10 * sizeof(int));
 7     x[10] = 0;
 8 }
 9 int main(void)
10 {
11     f();
12     return 0;
13 }
测试代码
复制代码

控制台:

 

 

==4642== Memcheck, a memory error detector
==4642== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4642== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==4642== Command: ./a
==4642==
==4642== Invalid write of size 4
==4642== at 0x10916B: f (a.c:7)
==4642== by 0x109180: main (a.c:11)
==4642== Address 0x4a50068 is 0 bytes after a block of size 40 alloc'd
==4642== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4642== by 0x10915E: f (a.c:6)
==4642== by 0x109180: main (a.c:11)
==4642==
==4642==
==4642== HEAP SUMMARY:
==4642== in use at exit: 40 bytes in 1 blocks
==4642== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==4642==
==4642== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4642== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4642== by 0x10915E: f (a.c:6)
==4642== by 0x109180: main (a.c:11)
==4642==
==4642== LEAK SUMMARY:
==4642== definitely lost: 40 bytes in 1 blocks
==4642== indirectly lost: 0 bytes in 0 blocks
==4642== possibly lost: 0 bytes in 0 blocks
==4642== still reachable: 0 bytes in 0 blocks
==4642== suppressed: 0 bytes in 0 blocks
==4642==
==4642== For lists of detected and suppressed errors, rerun with: -s
==4642== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

posted @   星明勇往直前  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示