编程语言爱好者

工具 | Valgrind + KCacheGrind,应用程序

2018-08-23  本文已影响33人  新手毛毛

写在前面
笔者在学习期间,偶遇这两个工具,经过上网检索资料学习使用,被其强大的功能深深折服。特写此文推荐,牛x不多吹了,请读者继续阅读。
本文内容概览

  • 写在前面
  • Valgrind & KCacheGrind 简介
  • 工具安装
  • 应用程序错误检查
  • 应用程序分析(代码分析、性能分析等)

1 Valgrind & KCacheGrind 简介

1.1 Valgrind

更多信息,请到Valgrind官方网址了解。

1.2 KCacheGrind

更多信息,请到KCacheGrind官方网址了解。

2 工具安装

笔者开发环境在XUbuntu系统里,通过包管理器安装工具非常方便

sudo apt install valgrind kcachegrind

3 应用程序错误检查

program main 
  implicit none   
  integer,allocatable :: a(:)
  a = [1,2,3,4,5]
  write(*,*) a(6)
end program main   
gfortran -g -O0 main.f90   # 生成调试信息,不优化可以获得更好的检测结果
valgrind --tool=memcheck --leak-check=full --log-file=memchk.log ./a.out 

==4827== Memcheck, a memory error detector
==4827== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4827== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4827== Command: ./a.out
==4827== Parent PID: 1770
==4827==
==4827== Invalid read of size 4
==4827== at 0x4FD60B0: ??? (in /usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0)
==4827== by 0x4FD6280: ??? (in /usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0)
==4827== by 0x4FDAD1D: ??? (in /usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0)
==4827== by 0x4FDBB74: ??? (in /usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0)
==4827== by 0x108A01: MAIN__ (main.f90:6)
==4827== by 0x108A53: main (main.f90:7)
==4827== Address 0x5e05ad4 is 0 bytes after a block of size 20 alloc'd
==4827== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4827== by 0x108942: MAIN__ (main.f90:4)
==4827== by 0x108A53: main (main.f90:7)
==4827==
==4827==
==4827== HEAP SUMMARY:
==4827== in use at exit: 20 bytes in 1 blocks
==4827== total heap usage: 22 allocs, 21 frees, 13,516 bytes allocated
==4827==
==4827== 20 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4827== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4827== by 0x108942: MAIN__ (main.f90:4)
==4827== by 0x108A53: main (main.f90:7)
==4827==
==4827== LEAK SUMMARY:
==4827== definitely lost: 20 bytes in 1 blocks
==4827== indirectly lost: 0 bytes in 0 blocks
==4827== possibly lost: 0 bytes in 0 blocks
==4827== still reachable: 0 bytes in 0 blocks
==4827== suppressed: 0 bytes in 0 blocks
==4827==
==4827== For counts of detected and suppressed errors, rerun with: -v
==4827== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

黑体部分是检查出的错误内容(虽然这段代码本身运行没有问题,但是新规范加入的内容使用起来容易出错)

4 应用程序分析(代码分析、性能分析等)

module myFun
  implicit none 
contains
  subroutine sub( a )
    integer :: a(:)
    a = 100
  end subroutine sub 
end module 

program main 
  use myFun
  implicit none   
  integer,allocatable :: a(:)
  
  allocate( a(5) )
  a = 0
  call sub( a )
  write(*,*) a
  deallocate(a)
end program main   
valgrind --tool=callgrind -v ./a.out 
  • 左侧包含性能分析选项
  • 右边可以显示源代码和实际运行指令,还能生成调用图。
分析结果

祝各位读者0 Error(s) 0 Warning(s)

上一篇 下一篇

猜你喜欢

热点阅读