更优雅的C语言溢出检测

关注微信公众号塔容万物

创建conda环境

# 适用于 glibc-2.17版本
conda create -n sanitizer libsanitizer gcc gxx

激活conda环境

conda activate sanitizer

测试代码

// main.c

typedef struct {
    int r;
    int g;
    int b;
}color_t;


color_t*
use_stack_ptr()
{
    color_t color = { 255, 255, 255 };
    return &color;
}

void
main()
{
    color_t* color = use_stack_ptr();
    color->r = 255;  // 溢出
}

编译代码

gcc -fsanitize=address -g -o main main.c
./main

可以发现,sanitizer可以检测到代码中的溢出,并给出发生错误的位置和具体类型。

AddressSanitizer:DEADLYSIGNAL
=================================================================
==1066210==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x6552a6930325 bp 0x7fffa3b86230 sp 0x7fffa3b86220 T0)
==1066210==The signal is caused by a WRITE memory access.
==1066210==Hint: address points to the zero page.
    #0 0x6552a6930325 in main /home/dwpeng/project/blog/test.c:19
    #1 0x7742e9846249 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #2 0x7742e9846304 in __libc_start_main_impl ../csu/libc-start.c:360
    #3 0x6552a69300a0 in _start (/home/dwpeng/project/blog/main+0x10a0)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /home/dwpeng/project/blog/test.c:19 in main