2016-11-15 88 views
2

我在嘗試使用fscanf從文件讀入字符串時遇到分段錯誤錯誤,任何幫助將不勝感激。fscanf分割錯誤 - C

int main() 
{ 
    char temp[100]; 
    FILE *fp = fopen("test.txt", "r"); 

    if (fp == NULL) 
    { 
     printf("error"); 
    } 

    memset(temp, 0, strlen(temp)); 

    while (fscanf(fp,"%s", temp)==1) 
    { 

    } 

return 0; 
} 
+0

輸入文件的內容是什麼? (它可能有超過99個字符的字符串嗎?) – davmac

+5

除了其他的評論和回答:'memset(temp,0,strlen(temp));'當你'fscan'變成'temp'時並不需要,無論如何。 –

+0

@MichaelWalz爲了安全起見,我仍然認爲在'char'數組的開頭至少有一個空終止符是一個好主意。 –

回答

2

在調用strlen(temp)temp是未定義的內容。

相反,使用char temp[100] = {0};並根本不使用memset

+3

請注意,在這種情況下'strlen(temp)'將返回零,所以'memset'不會執行任何操作。而且,'temp'在調用'fscanf'之前不需要被初始化。 –

+0

@DrewMcGowen謝謝,我明確提到刪除對'memset'的調用。 –

+0

@SanchkeDellowar我是如何迴應評論的。 –

-2

擺脫memset(temp, 0, strlen(temp));

char temp[100] = {};

+0

您複製了我的答案,甚至沒有打擾包括代碼無效的原因。 –

+0

您實際上並不需要替換聲明,因爲'fscanf'不關心內容。 –

3

strlen函數替換char temp[100];沒有的東西沿着這些路線:

int strlen(char *s) 
{ 
    int len = 0; 
    while(*s++) len++; 
    return len; 
} 

換句話說,它將返回第一個空字符的位置它遇到。如果你還沒有初始化你的字符串,那麼指針可能會從數組邊界增加到進程內存的其他部分以尋找空終止符(這會導致段錯誤)。

要解決此問題,請將參數替換爲memsetsizeof(temp)

+2

雖然你確實解釋了爲什麼代碼存在分段錯誤,但你應該詳細說明並演示如何解決該問題。 – BlueMoon93

+0

@ BlueMoon93固定:) –

1

它與strlen函數的問題,你能解決這個問題是這樣的:

int main() 
{ 
    char temp[100]; 
    FILE *fp = fopen("test.txt", "r"); 

    if (fp == NULL) 
    { 
     printf("error"); 
    } 

    memset(temp, 0, sizeof(temp)); //use sizeof instead of strlen is enough 

    while (fscanf(fp,"%s", temp)==1) 
    { 

    } 

return 0; 
}