簡體   English   中英

段故障(核心轉儲)錯誤

[英]Segment Fault (Core Dump) Error

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

void stringReverse(char* s){
    char tmp;
    int i = 0;
    int j = (strlen(s)-1);
    while(i>=j){
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
        i++;
        j--;
    }

}

int main(int argc, char* argv[]){
    FILE* in; /* file handle for input */
    FILE* out; /* file handle for output */
    char word[256]; /* char array to store words from the input file */

   /* checks that the command line has the correct number of argument */
    if(argc !=3){
        printf("Usage: %s <input file> <output file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* opens input file for reading */
    in = fopen(argv[1], "r");
    if(in==NULL){
        printf("Unable to read from file %s\n", argv[1]);
    }

    /* opens ouput file for writing */
    out = fopen(argv[2], "w");
    if(out==NULL){
        printf("Unable to read from file %s\n", argv[2]);
        exit(EXIT_FAILURE);
    }

    /* reads words from the input file and reverses them and prints them on seperate lines to the output file */
    while(fscanf(in, " %s", word) != EOF) {
        stringReverse(word);
        fprintf(out, "%s\n", word);
    }

    /* closes input and output files */
    fclose(in);
    fclose(out);

    return(EXIT_SUCCESS);
}

我不斷收到段錯誤(核心轉儲)錯誤。 我究竟做錯了什么? 我的out文件也返回為空,這不應該發生。

我的輸入是

abc def ghij 
klm nopq rstuv 
w xyz

並且輸出應該是

cba 
fed 
jihg 
mlk  
qpon  
vutsr 
w  
zyx

當然,您應該花一些時間來學習使用gdbvalgrind 至於代碼,不是在第9行是while(i<=j)而不是while(i>=j)嗎?

說明:

實際上,Barmar和Loginn之間的討論在解釋為何分段錯誤在這里發生時確實起到了很好的作用。 邏輯while(i>=j)是錯誤的,但是除非在輸入文件中包含單個字符(例如,示例輸入中的“ w”),否則不會出現分段錯誤。 為什么單個字符輸入會導致分段錯誤? 因為然后您從滿足循環條件的i = 0和j = 0開始循環,然后進入也滿足錯誤循環條件的i = 1和j = -1。 此時,嘗試訪問無效地址( s[-1] )將導致分段錯誤。

如果輸入文件中沒有任何單個字符,則程序將只運行並打印輸出文件中的單詞。 它不會反轉任何單詞,因為由於條件錯誤,代碼不會進入進行反轉的while循環。 但這也不會引起任何分段錯誤。

我希望我已經解釋清楚了。

暫無
暫無

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

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