爲什麼下面的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