Valgrind使用1:添加一个程序并且运行

本文目的

简单的介绍一下valgrind是什么,有什么用,怎么用

前置知识点

  1. linux基本知识
  2. C++基本语法基础
  3. cmake基础(因为这里编译用的是cmake,懒得用make或者gcc了)

valgrind工具简介

相关内容参考Valgrind Home

Valgrind是一个用于构建动态分析工具的工具框架。有一些Valgrind工具可以自动检测许多内存管理和线程错误,并详细介绍您的程序。您也可以使用Valgrind来构建新的工具。

和GDB有点类似,专门用于检测程序的内存和线程错误,有非常多的功能

debug模式和release模式的区别

  • Debug:调试版本:包含调试信息,所以容量比Release大很多,并且不进行任何优化(优化会使调试复杂化,因为源代码和生成的指令间关系会更复杂),便于程序员调试。
  • Release:发布版本:不对源代码进行调试,编译时对应用程序的速度进行优化,使得程序在代码大小和运行速度上都是最优的。
  • 只有debug模式下才可以使用gdb进行进程的调试

使用Valgrind进行调试一个文件

1. 编写一个程序

这个代码是有问题的,这才值得Valgrind去调试

//NULL.c
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
	int * ptr = NULL;
	*ptr = 1;
	return 0;
}

2. 编译该程序

编译的方式有很多中,gcc,cmake,make都可以。
需要在debug模式下编译
cmake需要debug的时候加入了这样一句话

set(CMAKE_BUILD_TYPE "Debug")

3. 直接运行该程序

NULL.c这个文件被我们编译成了名字叫做NULL的目标文件
会报Segmentation fault

./NULL
Segmenttion fault  (core has been dumped)

4. 使用Valgrind检测无效内存访问并且查看调试结果

NULL.c这个文件被我们编译成了名字叫做NULL的目标文件
相关命令如下,查询–help发现,内存管理如下

    --leak-check=no|summary|full     search for memory leaks at exit?  [summary]

运行


valgrind --leak-check=full ./NULL
==13891== Memcheck, a memory error detector
==13891== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==13891== Using Valgrind-3.21.0 and LibVEX; rerun with -h for copyright info
==13891== Command: ./NULL
==13891== 
==13891== Invalid write of size 4
==13891==    at 0x1086F7: main (in /home/monchell/Mon_workspace/project/draft/build/bin/NULL)
==13891==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==13891== 
==13891== 
==13891== Process terminating with default action of signal 11 (SIGSEGV)
==13891==  Access not within mapped region at address 0x0
==13891==    at 0x1086F7: main (in /home/monchell/Mon_workspace/project/draft/build/bin/NULL)
==13891==  If you believe this happened as a result of a stack
==13891==  overflow in your program's main thread (unlikely but
==13891==  possible), you can try to increase the size of the
==13891==  main thread stack using the --main-stacksize= flag.
==13891==  The main thread stack size used in this run was 8388608.
==13891== 
==13891== HEAP SUMMARY:
==13891==     in use at exit: 0 bytes in 0 blocks
==13891==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==13891== 
==13891== All heap blocks were freed -- no leaks are possible
==13891== 
==13891== For lists of detected and suppressed errors, rerun with: -s
==13891== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
段错误 (核心已转储)

会告诉你在main函数出现了segementation fault 的问题,而且是4个字节的写无效行为

valgrind其他用法

也可以检测内存泄漏和线程相关的问题。

参考文献

Valgrind Home

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值