前言
在做LeetCode题时发现一个有趣的事情。
对于C语言来说,如果直接访问超出Index的数组,会报错:
int main(int argc, char **argv) {
int array [100];
array[101] = -1;
int res = array[-1];
return res;
}
报错如下:
Runtime Error:
Line 3: Char 10: runtime error: index 101 out of bounds for type 'int [100]' (solution.c)
但是如果你使用malloc分配空间给int数组,index的越界访问是不会直接报错的
Heap-buffer-overflow
但是LeetCode 使用了AddressSanitizer检查是否存在内存非法访问
#include <stdlib.h>
int main(int argc, char **argv) {
int *array = (int*)malloc(100 * sizeof(int));
array[0] = -1;
int res = array[-1]; // BOOM
return res;
}
LeetCode 报错如下:
=================================================================
==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000000c at pc 0x000000401749 bp 0x7ffc91bd0570 sp 0x7ffc91bd0568
WRITE of size 4 at 0x60300000000c thread T0
#3 0x7ff2c35d42e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
0x60300000000c is located 4 bytes to the left of 20-byte region [0x603000000010,0x603000000024)
allocated by thread T0 here:
#0 0x7ff2c4a5e2b0 in malloc (/usr/local/lib64/libasan.so.5+0xe82b0)
#4 0x7ff2c35d42e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
Shadow bytes around the buggy address:
0x0c067fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c067fff8000: fa[fa]00 00 04 fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa