DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一 代码

 
#include<iostream>
 
#include<stdlib.h>
 
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检测出来了。

 
posted on 2023-04-20 14:14  DoubleLi  阅读(24)  评论(0编辑  收藏  举报