GDB调试之内存检查(二十二)

一、内存泄漏检测

内存泄漏检测常用命令:

  • call malloc_stats()
  • call malloc_info(0, stdout)

调试代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <malloc.h>
#include <string.h>
#include <thread>
#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
using namespace std;
 
void test_malloc_leak(int size)
{
    malloc(1024);
}
void no_leak()
{
    void *p=malloc(1024*1024*10);
    free(p);
}
int main(int argc,char* argv[])
{
    no_leak();
    test_malloc_leak(1024);
    return 0;
}

call malloc_stats()的使用:

call malloc_info(0, stdout)函数的使用:

二、内存检查

gcc选项 -fsanitize=address:

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

调试代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
void new_test()
{
    int *test = new int[80];
    test[0]=0;
}
void malloc_test()
{
    int *test =(int*) malloc(100);
    test[0]=0;
}
void heap_buffer_overflow_test()
{
    char *test = new char[10];
    const char* str = "this is a test string";
    strcpy(test,str);
    delete []test;
 
}
void stack_buffer_overflow_test()
{
    int test[10];
    test[1]=0;
    int a = test[13];
    cout << a << endl;
 
}
int global_data[100] = {0};
void global_buffer_overflow_test()
{
    int data = global_data[102];
    cout << data << endl;
 
}
void use_after_free_test()
{
    char *test = new char[10];
    strcpy(test,"this test");
    delete []test;
    char c = test[0];
    cout << c << endl;
}
int main()
{
    //new_test();
    //malloc_test();
     
    //heap_buffer_overflow_test();
     
    //stack_buffer_overflow_test();
    //global_buffer_overflow_test();
    use_after_free_test();
     
    return 0;
}

一旦在运行过程中出现内存泄漏的问题,就会把详细信息打印出来

  

 
posted @   TechNomad  阅读(1302)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示