簡體   English   中英

fscanf分段錯誤-C

[英]fscanf Segmentation fault - C

我在嘗試使用fscanf從文件讀取為字符串時遇到分段錯誤錯誤,我們將不勝感激。

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;
}

在對strlen(temp)的調用中, temp具有未定義的內容。

而是使用char temp[100] = {0}; 並且根本不使用memset

strlen函數遵循以下原則:

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

換句話說,它將返回遇到的第一個空字符的位置。 如果尚未初始化字符串,則指針可能會從數組邊界增加並進入進程內存的其他部分,以查找空終止符(這使它成為段錯誤)。

要解決此問題,請使用sizeof(temp)替換memset的參數。

這是與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;
}

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

替換char temp[100]; 使用char temp[100] = {};

暫無
暫無

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

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