gdb内存检查

内存检查

gcc选项 -fsanitize=address

  • 检查内存泄漏
  • 检查堆溢出
  • 检查栈溢出
  • 检查全局内存溢出
  • 检查释放后再使用

示例代码

https://github.com/SimpleSoft-2020/gdbdebug/memcheck-section

检查内存泄漏

gdb memcheck-section -q

gdb内存检查_第1张图片

检查堆溢出

15525ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000001a at pc 0x7ffff6e7e3a6 bp 0x7fffffffe080 sp 0x7fffffffd828
gdb内存检查_第2张图片

检查栈溢出

16569ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffe054 at pc 0x5555555553de bp 0x7fffffffdfe0 sp 0x7fffffffdfd0

gdb内存检查_第3张图片

检查全局内存溢出

18552ERROR: AddressSanitizer: global-buffer-overflow on address 0x5555557564f8 at pc 0x5555555554b1 bp 0x7fffffffe0c0 sp 0x7fffffffe0b0
gdb内存检查_第4张图片

小结

C++中,字符串存放在数组存放在全局变量存放在内存的全局存储区

检查释放后再使用

gdb内存检查_第5张图片

内存泄漏检查

call malloc_stats()
call malloc_info(0,stdout)

示例代码

https://github.com/SimpleSoft-2020/gdbdebug/memleak-section

gdb内存检查_第6张图片
命令

(gdb) l
6       #include 
7       #include 
8       using namespace std;
9
10      void test_malloc_leak(int size)
11      {
12              malloc(1024);
13      }
---Type <return> to continue, or q <return> to quit---
14      void no_leak()
15      {
(gdb) b 16
Breakpoint 1 at 0x11d1: file main.cpp, line 16.
(gdb) r
Starting program: /root/cpp_project/gdb_project/gdbdebug/memleak-section/memleak-section 

Breakpoint 1, no_leak () at main.cpp:16
16              void *p=malloc(1024*1024*10);
(gdb) call malloc_stats()
Arena 0:
system bytes     =     135168
in use bytes     =      73312
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      73312
max mmap regions =          0
max mmap bytes   =          0
(gdb) n
17              free(p);
(gdb) call malloc_stats()
Arena 0:
system bytes     =     135168
in use bytes     =      73312
Total (incl. mmap):
system bytes     =   10625024
in use bytes     =   10563168
max mmap regions =          1
max mmap bytes   =   10489856
(gdb) n
18      }
(gdb) call malloc_stats()
Arena 0:
system bytes     =     135168
in use bytes     =      73312
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      73312
max mmap regions =          1
max mmap bytes   =   10489856
(gdb) n
main (argc=1, argv=0x7fffffffe1c8) at main.cpp:22
22              test_malloc_leak(1024);
(gdb) call malloc_stats()
Arena 0:
system bytes     =     135168
in use bytes     =      73312
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      73312
max mmap regions =          1
max mmap bytes   =   10489856
(gdb) n
23              return 0;
(gdb) call malloc_stats()
Arena 0:
system bytes     =     135168
in use bytes     =      74352
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      74352
max mmap regions =          1
max mmap bytes   =   10489856
(gdb) p 74352-73312
$1 = 1040
(gdb) c
Continuing.
[Inferior 1 (process 22209) exited normally]
(gdb) p 74352-73312
$2 = 1040

你可能感兴趣的:(linux下gdb调试,c++,linux)