簡體   English   中英

C-fgets在使用char數組時神秘地導致segfault

[英]C - fgets mysteriously causes segfault when using char arrays

我似乎已經對此問題提出了類似的問題,但是我以一種非常直接的方式詢問,因此希望我能對到底發生了什么有個很好的解釋。

看一下這個非常簡單的程序:

int main()
{
    char* a;
    a[200];
    fgets(a, 200, stdin);

    char* b;
    b[200];
    fgets(b, 200, stdin); // Seg fault occurs once I press enter

    return 0;
};

如您所見,“ a”部分運行正常。 但是,“ b”段存在故障。 到底是怎么回事?

好吧,這是這里的基礎。 segfault意味着您正在使用您無權訪問的內存。

int main()
{
    char* a; // Create a pointer (a pointer can only contains an address (int size)
    a[200]; // Trying to access to the byt 200 of your pointer but basicaly do nothing. You are suppose to have a segfault here

    fgets(a, 200, stdin); // store your stdin into &a (you may have a segfault here too)

    return 0;
};

取決於很多事情,有時可能會失敗,有時不會失敗。 但是您在這里做錯了。 您必須設法解決此問題。 首先使用一個簡單的數組char

#include <stdio.h> /* for stdin */
#include <stdlib.h> /* for malloc(3) */
#include <string.h> /* for strlen(3) */
#include <unistd.h> /* for write(2) */

int main()
{
     char str[200];
     fgets(str, sizeof str, stdin);

     write(1, str, strlen(str)); /* you can receive less than the 200 chars */

     return (0);
}

或者,如果您想繼續使用指針

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

int main()
{
     const size_t sz = 200;
     char* str;
     str = malloc(sz);

     fgets(str, sz, stdin);

     write(1, str, strlen(str));
}

但是無論如何,您的錯誤是由於對C語言中的指針和內存缺乏了解導致的。

祝你好運

暫無
暫無

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

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