1. 程式人生 > >【Linux開發】GCC 4.8及以上支援記憶體非法訪問檢查

【Linux開發】GCC 4.8及以上支援記憶體非法訪問檢查

gcc4.8及以上版本支援地址越界,野指標檢查,只需要在編譯時使用-fsanitize=address選項即可,當執行程式時如果訪問非本程式申請的地址就會報錯。
[email protected]:/home/ngos/practice> vi nullpoint.c
      1 #include "stdio.h"
      2
      3 int main(int argc , char **argv)
      4 {
      5         int *p = NULL;
      6         *p = 10;
      7         printf("%d",*p);
      8
      9         return 0;
     10 }

[email protected]:/home/ngos/practice> gcc -g  -fsanitize=address -o nullpoint nullpoint.c
[email protected]:/home/ngos/practice> ls
nullpoint  nullpoint.c
[email protected]:/home/ngos/practice> ./nullpoint
ASAN:SIGSEGV
=================================================================
==3696==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x00000040085a sp 0x7fff603db8b0 bp 0x7fff603db8d0 T0)
    #0 0x400859 in main /home/ngos/practice/nullpoint.c:6
    #1 0x7faa9bd19b5d in __libc_start_main (/lib64/libc.so.6+0x1eb5d)
    #2 0x4006c8 (/home/ngos/practice/nullpoint+0x4006c8)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /home/ngos/practice/nullpoint.c:6 main
==3696==ABORTING
由上面的錯誤提示資訊可以看到第6行存在指標錯誤。