为什么下面的C代码允许输入流大于缓冲区的大小,最终导致分段错误?使用字符数组1的大小为very_bad
的参数,是不是只允许输入1个字符?流缓冲区大小小于输入流,但没有立即分段错误
此外,初始化c
作为int
而不是char
会有什么影响?陈述while ((c = getchar()) != '\n' && c != EOF)
将以getchar()
以4个字符为增量进行读取?或者字符的二进制表示是否在4字节?
注意:这是来自课程的文本,但不是HW。
#include <stdio.h>
void very_bad(char* buffer) {
int c; /* NB: int rather than char because the system I/O function
getchar() returns the int value 0xffffffff on end-of-file */
char* dest = buffer;
/* read until newline or end-of-file (Control-Z for the standard input) */
while ((c = getchar()) != '\n' && c != EOF)
*dest++ = c; /* store next character in buffer and move pointer */
printf("%s\n", buffer);
}
int main() {
char buff[1]; /* big trouble waiting to happen */
very_bad(buff);
return 0;
}
缺口区域用于对齐。 – BLUEPIXY 2014-10-10 12:58:22
单词:UB - http://en.wikipedia.org/wiki/Undefined_behavior – 2014-10-10 12:59:02
在评论中解释了int的基本原理。 'getchar'读取一个字节,并将其无符号表示形式返回为int,范围为0到255.它返回特殊值'EOF',即-1,表示该流已用完。 char不能存储所有有效的字符和一个额外的值,因此'getchar'使用'int'。 (实际上,使用'char'可能会让你错过文件的结尾。) – 2014-10-10 13:55:17