Skip to main content
1 / 3
user avatar
user avatar

既にクローズされていますので参考までに。

gcc には sanitize オプションというものがありまして、その内の一つに配列変数などの宣言領域を超えるアクセス(out-of-bounds access)を実行時に検出する機能があります。具体的には -fsanitize=address を付けてコンパイルします。

$ gcc -std=gnu99 -Wall -fsanitize=address -g cloth.c -o cloth
$ ./cloth
4
=================================================================
==26858==ERROR: AddressSanitizer: stack-buffer-overflow on address 0xbfe95522 ...
WRITE of size 3 at 0xbfe95522 thread T0
    #0 0xb71e211b  (/usr/lib/i386-linux-gnu/libasan.so.3+0x4311b)
    #1 0xb71e2cab in __isoc99_vscanf (/usr/lib/i386-linux-gnu/libasan.so.3+0x43cab)
    #2 0xb71e2d27 in __interceptor___isoc99_scanf (...
    #3 0x804892f in main cloth.c:26  <== "int scanf_count = scanf("%2s", card);"
    #4 0xb7001636 in __libc_start_main (/lib/i386-linux-gnu/libc.so.6+0x18636)
    #5 0x8048780  (cloth+0x8048780)

Address 0xbfe95522 is located in stack of thread T0 at offset 194 in frame
    #0 0x804886a in main cloth.c:20  <== "main function frame"

  This frame has 3 object(s):
    [32, 136) 'player_list'
    [192, 194) 'card' <== Memory access at offset 194 overflows this variable
    [256, 270) 'card_left'

char card[3]; に修正すると、上記のエラーメッセージは出力されなくなります。

ところで、これは GNU C ライブラリの拡張機能なのですが、scanf(3) の書式文字列に %ms を使うことができます。この場合、配列変数を用意する必要がなくなります。

scanf(3)

NOTES

The 'a' assignment-allocation modifier
Originally, the GNU C library supported dynamic allocation for string inputs (as a nonstandard extension) via the a character. (This feature is present at least as far back as glibc 2.0.) Thus, one could write the following to have scanf() allocate a buffer for an input string, with a pointer to that buffer being returned in *buf:

char *buf;
scanf("%as", &buf);

The use of the letter a for this purpose was problematic, since a is also specified by the ISO C standard as a synonym for f (floating-point input). POSIX.1-2008 instead specifies the m modifier for assignment allocation (as documented in DESCRIPTION, above).
Support for the m modifier was added to glibc starting with version 2.7, and new programs should use that modifier instead of a.

user39889