gcc に限って言えば、以下の様なマクロを追加して -O2
オプション(optimize level 2)を付けてコンパイルすると warning を表示してくれます。
#define strlen(s) (sizeof(s)/sizeof(s[0]))
# まぁ、何の意味も無い事ではありますが
$ gcc -O2 -Wall -o example example.c
example.c: In function ‘main’:
example.c:12:19: warning: array subscript is above array bounds [-Warray-bounds]
printf("%c\n", s[strlen(s) - 1 - len]); // (2)
ところで、gcc には実行時に配列の領域外アクセスをチェックするためのオプションスイッチがあります(-fsanitize=address
オプション)。
$ gcc --version
gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2
$ gcc -O2 -g -Wall -fsanitize=address -o example example.c
$ ./example
len: 6
=================================================================
==18994==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x7ffd971e6c1f at pc 0x400940 bp 0x7ffd971e6bf0 sp 0x7ffd971e6be0
READ of size 1 at 0x7ffd971e6c1f thread T0
#0 0x40093f in main example.c:12
#1 0x7f5778126a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f)
#2 0x4009d8 in _start (example+0x4009d8)
Address 0x7ffd971e6c1f is located in stack of thread T0 at offset 31 in frame
#0 0x40086f in main example.c:7
This frame has 1 object(s):
[32, 38) 's' <== Memory access at offset 31 underflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow example.c:12 main
Shadow bytes around the buggy address:
0x100032e34d30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34d40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34d50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34d60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34d70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x100032e34d80: f1 f1 f1[f1]06 f4 f4 f4 00 00 00 00 00 00 00 00
0x100032e34d90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34da0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34db0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34dc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100032e34dd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Contiguous container OOB:fc
ASan internal: fe
==18994==ABORTING
printf("%c\n", s[-1]);
は警告は出るかもしれませんが-Werror
等を指定しない限りコンパイルエラーにはならないはずです。s[-1]
のようなアクセスが行われた結果は動作未定義です。