gets(3)
危険であり、絶対に避ける必要があります。セキュリティ上の欠陥gets(3)
がない場合の使用は想定できません。
scanf(3)
%s
も危険です。割り当てたバッファのサイズを示すには、「フィールド幅」指定子を使用する必要があります。フィールド幅がないと、このルーチンは次のように危険gets(3)
です。
char name[64];
scanf("%63s", name);
GNU Cライブラリは、バッファを割り当てるa
修飾子を提供します。%s
この移植性のない拡張機能は、おそらく正しく使用するのがそれほど難しくありません。
The GNU C library supports a nonstandard extension that
causes the library to dynamically allocate a string of
sufficient size for input strings for the %s and %a[range]
conversion specifiers. To make use of this feature, specify
a as a length modifier (thus %as or %a[range]). The caller
must free(3) the returned string, as in the following
example:
char *p;
int n;
errno = 0;
n = scanf("%a[a-z]", &p);
if (n == 1) {
printf("read: %s\n", p);
free(p);
} else if (errno != 0) {
perror("scanf");
} else {
fprintf(stderr, "No matching characters\n"):
}
As shown in the above example, it is only necessary to call
free(3) if the scanf() call successfully read a string.