gets(3)
是危险的,应该不惜一切代价避免。我无法想象没有安全漏洞的gets(3)
用途。
scanf(3)
's%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.