一 代码
using namespace std;
void func(){
int *x=(int *)malloc( 10 * sizeof ( int ) ) ;
x[10]=0;
}
int main(){
func();
cout<<"done"<<endl;
return 0;
}
二 编译并运行
[root@localhost charpter05]# g++ -g 0508test.cpp -o 0508
[root@localhost charpter05]# ./0508
done
三 用Valgrind检测非法访问内存
[root@localhost charpter05]# valgrind ./0508
==16719== Memcheck, a memory error detector
==16719== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16719== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==16719== Command: ./0508
==16719==
==16719== Invalid write of size 4
==16719== at 0x4008DE: func() (0508test.cpp:6)
==16719== by 0x4008EE: main (0508test.cpp:9)
==16719== Address 0x5a1a068 is 0 bytes after a block of size 40 alloc'd
==16719== at 0x4C29EC3: malloc (vg_replace_malloc.c:309)
==16719== by 0x4008D1: func() (0508test.cpp:5)
==16719== by 0x4008EE: main (0508test.cpp:9)
==16719==
done
==16719==
==16719== HEAP SUMMARY:
==16719== in use at exit: 40 bytes in 1 blocks
==16719== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==16719==
==16719== LEAK SUMMARY:
==16719== definitely lost: 40 bytes in 1 blocks
==16719== indirectly lost: 0 bytes in 0 blocks
==16719== possibly lost: 0 bytes in 0 blocks
==16719== still reachable: 0 bytes in 0 blocks
==16719== suppressed: 0 bytes in 0 blocks
==16719== Rerun with --leak-check=full to see details of leaked memory
==16719==
==16719== For lists of detected and suppressed errors, rerun with: -s
==16719== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
四 分析
1 16719表示的是进程号
2 版本信息
==16719== Memcheck, a memory error detector
==16719== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16719== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==16719== Command: ./0508
3 非法写内存,写操作内存是4个字节,发生错误时候的函数堆栈,说明错误发生在第6行
==16719== Invalid write of size 4
==16719== at 0x4008DE: func() (0508test.cpp:6)
==16719== by 0x4008EE: main (0508test.cpp:9)
4 程序泄露了40个字节的内存
==16719== LEAK SUMMARY:
==16719== definitely lost: 40 bytes in 1 blocks
==16719== indirectly lost: 0 bytes in 0 blocks
==16719== possibly lost: 0 bytes in 0 blocks
==16719== still reachable: 0 bytes in 0 blocks
==16719== suppressed: 0 bytes in 0 blocks
5 该程序存在两个问题,一个是fun函数动态申请的堆内存没有释放,另外一个是对堆内存访问越界。这两个问题都被valgrind检测出来了。
分类:
异常诊断与调试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-04-20 printk()函数的总结
2016-04-20 驱动程序调试方法之printk——自制proc文件(二)
2016-04-20 驱动程序调试方法之printk——自制proc文件(一)
2016-04-20 驱动程序调试方法之printk——printk的原理与直接使用
2014-04-20 VC添加背景图片 的一种方法