Valgrind使用1:添加一个程序并且运行
本文目的
简单的介绍一下valgrind是什么,有什么用,怎么用
前置知识点
- linux基本知识
- C++基本语法基础
- 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其他用法
也可以检测内存泄漏和线程相关的问题。