PTA拼题 提交代码时碰到的一点坑!!
在处理 解析字符串 类型问题的时候, 经常需要读入包含 空格 的长字符串, 在C语言中, 最初通常使用 gets 函数来读取包含空格的字符串, 但是在 C/C++11 中已被摒弃.

官方参考手册 给出以下解释:

Notes
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.

具体会出现怎样的错误呢:

1
2
3
4
5
6
int main() {
int str[5];
gets(str);
printf("%s\n", str);
return 0;
}

如果程序输入 1234 , 那么得到的输出显然是 1234 , 这没问题.
现在继续新的输入 12345678 , 同样可以得到相同的输出 12345678 .
但是, 如果输入内容继续加大, 比如 12345678901234567890 , 此时会得到这样一个输出:

1
2
3
4
warning: this program uses gets(), which is unsafe.
12345678901234567890
12345678901234567890
[1] 33006 segmentation fault "/Users/char_/test/"a

可以看到, 输入的字符串还是被原样输出了, 但是同时伴有一条 segmentation fault (段错误) 的信息被输出.

困了, 待续…..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdio>
#include <cstring>

int main() {
char a[5], b[5];
gets(a);
fgets(b, sizeof(b), stdin);

int lenA = strlen(a),lenB = strlen(b);
printf("lenA = %d, lenB = %d\n", lenA, lenB);
// print str a,b
int i = 0;
while(i < lenA) printf("%c_",a[i++]);
printf("\n");
i = 0;
while(i < lenB) printf("%c_",b[i++]);
printf("\n");

// print ascii of str a,b
i = 0;
while(i < lenA) printf("%d_",a[i++]);
printf("\n");
i = 0;
while(i < lenB)
printf("%d_",b[i++]);
return 0;
}