簡體   English   中英

調用fgets從文件讀取行時出現分段錯誤

[英]Segmentation fault when calling fgets to read lines from file

在調用fgets大約20次之后,我遇到了一個段錯誤。 我正在打開一個文件(不返回null)。 它的格式為:

 num1: value1
 num2: value2
 num3: value3

然后從文件中讀取行,將值存儲到數組中,使用nums作為位置。 以下是seg fault的代碼:

編輯:聲明myArray和line:

char myArray[3000];    
char * line;
char * word;

line = (char *) malloc(100);
word = (char *) malloc(16);

while(fgets(line, 99, file)) {
    printf("%s\n", line);
    word = strtok(line, " :");
    name = (int) strtol(word, NULL, 16);

    word = strtok(NULL, " \n");
    myArray[name] = word;
}

你會注意到我在收到后立即打印出這條線。 該文件有26行,但它只打印23行然后是seg錯誤。 現在,這是我對fgets不完全了解的事情,還是我得到的一些synthax不正確? 我已經嘗試將更多內存分配給行,或者更多地分配給單詞。 在每次調用strtok之后我都嘗試過malloc -ing更多內存,但似乎沒有什么能解決這個錯誤。

問題是線myArray[name] = word; 你從輸入行獲取一個數組索引,然后將該位置的字符設置為你單詞地址的低位...我懷疑這實際上是你想要做的。

您的代碼還有一些其他問題,您正在從行word = (char *) malloc(16);泄漏內存word = (char *) malloc(16); 因為strtok會將指針返回到您最初傳遞它的字符串中。 您實際上不需要為問題中所寫的代碼malloc任何內容,因此您可以:

char myArray[3000];    
char line[100];
char *word = NULL;

word必須是一個指針,因為它持有strtok()的結果

你顯然不明白指針,你需要先了解它,然后才能理解為什么你的代碼沒有按照你期望的方式工作。

如果你說你的代碼實際意味着什么,我可以給你一些關於如何解決它的提示,但目前我無法確定預期的結果是什么。

編輯:你打算用十六進制讀取你的數字嗎? strtol()的最后一個參數是用於轉換的基礎...你也可以只使用atoi()

所以你的循環看起來像:

char myArray[3000];    
char line[100];
char *word = NULL;


while(fgets(line, 100, file)) {
    printf("%s\n", line);
    word = strtok(line, " :");
    if(word == NULL) continue;
    name = atoi(word); /* only if you didn't actually want hexadecimal */

    word = strtok(NULL, " \n");
    if(word == NULL) continue;

    if(name > 0 && name < 3000) { /* as I said in a comment below */
        strncpy(myArray + name, word, 3000 - name);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM