简体   繁体   English

C-fgets在使用char数组时神秘地导致segfault

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

I've seem some similar questions to this one, however I'm asking in a very direct way so hopefully I can get a good explanation as to what the hell is going on. 我似乎已经对此问题提出了类似的问题,但是我以一种非常直接的方式询问,因此希望我能对到底发生了什么有个很好的解释。

Look at this very simple program: 看一下这个非常简单的程序:

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

As you can see, section 'a' runs fine. 如您所见,“ a”部分运行正常。 however section 'b' seg faults. 但是,“ b”段存在故障。 What is going on? 到底是怎么回事?

Well, this is basics here. 好吧,这是这里的基础。 A segfault means you are using memory you do not have access to it. 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;
};

Depending on many thing, sometimes it may fails, sometimes not. 取决于很多事情,有时可能会失败,有时不会失败。 But you are doing something wrong here. 但是您在这里做错了。 You have to way to fix this. 您必须设法解决此问题。 First using a simple array char 首先使用一个简单的数组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);
}

Or if you want to keep using pointers 或者,如果您想继续使用指针

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

But anyway, your mistake results from a lack of knowledge about pointer and memory in C. 但是无论如何,您的错误是由于对C语言中的指针和内存缺乏了解导致的。

Good luck with that, 祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM