簡體   English   中英

C程序中的分段錯誤,讀取文本文件

[英]Segmentation Fault in C program that read a text file

我正在寫一個小C程序,它讀取文本文件並在屏幕上打印它的內容。 我確實得到了打印件,但在打印結束時我遇到了分段錯誤。 另外,如果我取消注釋atoi功能,我只得到第一次打印,然后是分段錯誤。任何人都可以告訴我我的錯誤是什么?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h> /* For mode constants */
#include <sys/types.h>
#include <fcntl.h> /* For O_* constants */


int sudoku[9][9];

int main(int argc, char *argv[]){

    if(argc!=2){
        printf("error en numero de parametros, el directorio de archivo de sudoku.\n");
        return -1;
    }
    char *directorio = argv[1];
    //printf("el directorio es: %s \n", directorio);
    int fp;
    fp=open(directorio,O_RDWR);
    if(fp<0){
        printf("error al leer el archivo");
        return -1;
    }   

    char *data = mmap(0, 4096, PROT_READ, MAP_SHARED, fp,0);

    if (data == -1) {
        perror("mmap");
        exit(1);
    }
    int i=0;
    for(i=0; i<81 ; i++){
        printf("data : %c \n",data[i]);
        //int val =atoi(data[i]);
    }

    if ((munmap(data,4096)) != 0) perror("!mumap failed");
    fclose(fp);


}

如果我取消注釋atoi功能,我只得到第一次打印,然后是分段錯誤。

原因是atoi將參數作為char *,其原型是

int atoi(con​​st char * nptr);

當char作為參數傳遞時,char的ascii值被視為地址,該值將為(0-255)。 您沒有權限訪問這些位置,因此分段錯誤。

您遇到段錯誤的原因是因為您使用fclose()來關閉使用open()打開的文件。

int fclose(FILE *stream)fclose()的函數原型, int close(int fildes)close()的原型。

這意味着fclose()期望一個FILE指針但是正在接收你聲明為int的參數fp ,這就是導致你的段錯誤的原因。 程序試圖訪問fp值的內存地址位置,它沒有正確的訪問權限,因此是段錯誤。

我編譯並運行你的程序用close()替換fclose() ,我不再有任何段錯誤問題。

關於你的atoi()調用,這是由其他海報解釋的,是由於atoi(const char *str)需要一個char指針作為它的參數。 atoi()接收的不是char指針而是char變量,因此它不會被'\\0'字符終止,這是使用atoi()函數進行segfault的原因。

由於您一次操作一個字符,因此使用int val = data[i] - '0'更有意義。 C中的字符是整數類型,C標准不保證'0'的字符表示在所有實現中都是相同的,例如我機器上的數字零是48,'1'是49,2是50。然而,C標准確實表明,無論數字表示為字符,對於字符“0”到“9”,它們都將比之前的數字高1。 因此,做一小部分char數學你可以得出'2' - '0' = 2因為'2'是50(在這個系統上)而'0'是48。

暫無
暫無

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

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