内存泄漏检测工具asan

12 篇文章 0 订阅
6 篇文章 1 订阅

1、使用内存泄漏工具asan需要添加编译选项

 -Lasan -fsanitize=address -fsanitize-recover=address -fno-omit-frame-pointer

2、编写代码文件,如添加test_asan.c 

#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
void test()
{
    int* arr = (int*)malloc(sizeof(int) * 10);
}
int main()
{
    test();
    for(int i=0;i<10;i++)
    {
        sleep(1);
    }
    return 0;
}

3、编译代码

 gcc -g test_asan.c -o tt -Lasan -fsanitize=address -fsanitize-recover=address -fno-omit-frame-pointer

4、执行结果 

 

 5、常见的错误类型

1、内存泄漏(Memory leaks),即申请的内存未释放,如上图所示

2、栈溢出(Stack buffer overflow),函数中的变量,参数,引用,指针,返回地址等存储在栈中,若超出栈的容量会导致栈溢出,常见情形为递归过深或申请的数组过大。

#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
void test()
{
    int* arr = (int*)malloc(sizeof(int) * 10);
}

void stack_buffer_overflow(){
    long long len = 1024*1024*1024;
    double a[len];
    for(int i = 0; i < len; i++){
        a[i] = -1.0;
    }
    return;
}


int main()
{
//    test();
    stack_buffer_overflow();
    for(int i=0;i<10;i++)
    {
        sleep(1);
    }
    return 0;
}

 3.堆溢出(heap buffer overflow)。堆中存储动态申请内存,如malloc(), calloc(), new int[]等,常见情况为访问到申请内存之外的地址

#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
void heap_buffer_overflow(){
    int* a = (int*)malloc(sizeof(int)*10);
    a[11] = 1;
    return;
}

int main(){
    heap_buffer_overflow();
    return 0;
}

 

 4.全局溢出(Global buffer overflow)。
把超大静态数组/放到全局变量中或越界访问静态数组

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值