2014-10-10 39 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