2014-10-10 67 views
0

为什么下面的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; 
} 
+0

缺口区域用于对齐。 – BLUEPIXY 2014-10-10 12:58:22

+0

单词:UB - http://en.wikipedia.org/wiki/Undefined_behavior – 2014-10-10 12:59:02

+1

在评论中解释了int的基本原理。 'getchar'读取一个字节,并将其无符号表示形式返回为int,范围为0到255.它返回特殊值'EOF',即-1,表示该流已用完。 char不能存储所有有效的字符和一个额外的值,因此'getchar'使用'int'。 (实际上,使用'char'可能会让你错过文件的结尾。) – 2014-10-10 13:55:17

回答

1

对于问题的第一部分,它与操作系统中的页面大小有关。当然,该代码会导致“未定义的行为”。

这个答案给出了一个很好的主意: why doesn't my program crash when I write past the end of an array?

此外,什么是初始化C作为一个int ,而不是一个字符的含义是什么? while((c = getchar())!='\ n'& & c!= EOF)的语句是以4个字符为增量读取getchar()吗?或 将字符的二进制表示是在4个字节?

getchar()的protoype是:

int getchar (void); 

所以,当你使用c = getchar(),每次调用getchar()会读取从标准输入一个字符,转换是charint并返回,分配给变量为c