一个查看堆内存泄露的工具
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现