• 【应用】Linux内存调试工具:valgrind


    运行环境:ubuntu-20.04

    工具版本:valgrind-3.16.1

    1、工具自我介绍:

    Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. 

    更多信息请转到官网,最新版本下载点这里

    2、工具的编译与安装:

    解压进入到源码下,可以看下 README 指引,里面有写着编译安装的相关操作,笔者是直接在PC上运行,所以就默认操作了,没有自定义一些配置,不影响使用。

    实际操作命令:

    1 ./autogen.sh
    2 ./configure
    3 make -j
    4 make install

    autogen 时如果遇到 aclocal 找不到问题,可以 apt install automake 来解决。

    1 # valgrind --version
    2 valgrind-3.16.1

    OK,可以运行了,安装完毕。

    3、实例测试一下:

    先写个 BUG 吧,制造个溢出的情况:

    写 BUG 还不简单,来了,

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 int main()
     6 {
     7     char *str = "zackary";
     8     char *p = (char*)malloc(strlen(str));
     9 
    10     strcpy(p, str);
    11 
    12     free(p);
    13 
    14     return 0;
    15 }

    用 valgrind 检查一下,看看是怎么提示的。

    运行命令 valgrind --tool=memcheck --leak-check=full ./a.out

    检查结果如下:

    ==13257== Memcheck, a memory error detector
    ==13257== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==13257== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
    ==13257== Command: ./a.out
    ==13257==
    ==13257== Invalid write of size 1
    ==13257==    at 0x483ED4E: strcpy (vg_replace_strmem.c:511)
    ==13257==    by 0x1091EA: main (in /root/code/code_grind/a.out)
    ==13257==  Address 0x4a49047 is 0 bytes after a block of size 7 alloc'd
    ==13257==    at 0x483B7FB: malloc (vg_replace_malloc.c:307)
    ==13257==    by 0x1091D3: main (in /root/code/code_grind/a.out)
    ==13257==
    ==13257==
    ==13257== HEAP SUMMARY: 
    ==13257==     in use at exit: 0 bytes in 0 blocks
    ==13257==   total heap usage: 1 allocs, 1 frees, 7 bytes allocated
    ==13257==
    ==13257== All heap blocks were freed -- no leaks are possible
    ==13257==
    ==13257== For lists of detected and suppressed errors, rerun with: -s
    ==13257== ERROR SUMMARY: 1 errors from 1 contexts
    (suppressed: 0 from 0)

    如果运行结束后,工具有提示  Possible fixes: (1, short term): install glibc's debuginfo package on this machine.  please in future ship a non-stripped ld.so 那我们就搞一个 debug 版本的安装上即可 apt install libc6-dbg 

    安装后工具运行是成功的,所存在问题详情工具已经指出。只是简单的使用该工具目前来看没有什么问题了,

    深入使用和原理分析就日后吧。

  • 相关阅读:
    jq 的简单循环
    简单的下拉菜单
    jQ事件
    图片移动
    选中效果
    js 时间
    简单的密码验证
    DOM 的简介 和一些方法
    Java编程思想笔记
    Java并发笔记(二)
  • 原文地址:https://www.cnblogs.com/GyForever1004/p/13909270.html
Copyright © 2020-2023  润新知