2017-02-18 54 views
0

我試圖使此代碼爲了從文件中讀取希臘字母並打印使用fscanf發聲的英文字母。問題是我不斷收到分段錯誤。我錯過了什麼?使用fscanf分段錯誤 - 不分配內存問題

#include <stdio.h> 

int main() 
{    
    char s[100];  
    int i; 
    FILE * myfile; 

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r"); 

    while(fscanf(myfile, "%s", s) == 1) 
     { 
      for (i=0 ; i<100 ; i++) 
       { 
        if (s[i] == 'Α') 
         { printf("A") ; } 
        else 
        if (s[i] == 'Β') 
         { printf("V") ; } 
     } 
} 
+2

步驟1:'的fscanf(MYFILE, 「%s」 時,S)' - >'的fscanf(MYFILE, 「%99S」,S)',以防止緩存器溢出。 – chux

+1

不要訪問傳遞讀取的數據。 (for =(i = 0; i <100; i ++)' - >'for(i = 0; s [i]; i ++)'。需要查看哪些輸入用於診斷分段故障。同時測試'myfile == NULL'。 – chux

+2

檢查'fopen'的返回值。 – BLUEPIXY

回答

1

您的代碼有3個嚴重問題。

1)您從不檢查fopen是否成功。

2)您可能會讀取未初始化的簽名數據。

3)你可能會溢出在輸入緩衝區

所有三件事情可能會導致程序失敗。

嘗試這些變化:

#include <stdio.h> 
#include <string.h> 

int main() 
{    
    char s[100];  
    int i; 
    FILE * myfile; 

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r"); 

    // Check that fopen went fine 
    if (!myfile) 
    { 
     printf("Failed to open file\n"); 
     return 1; 
    } 

    while(fscanf(myfile, "%99s", s) == 1) 
         // ^^ 
         // Never read more than 99 chars (i.e. 99 + a terminating null byte) 
     { 
      for (i=0 ; i<strlen(s) ; i++) 
         // ^^^^^^ 
         // Only iterate over the valid chars 
       { 
        if (s[i] == 'Α') 
         { printf("A") ; } 
        else 
        if (s[i] == 'Β') 
         { printf("V") ; } 
     } 
} 
+0

我試試這個確切的代碼。首先,它沒有識別strlen(s),當我用一開始就將它取代時,我得到了分段錯誤 –

+0

哦,你是對的..但是,只是嘗試過它仍然是分段錯誤 –

+0

更新:我忘記了寫一行它確實返回無法打開文件。所以我該怎麼做? –