C - fgets 在使用 char 数组时神秘地导致段错误

标签 c segmentation-fault fgets

我似乎遇到了一些与此类似的问题,但我以一种非常直接的方式提问,希望我能就到底发生了什么得到一个很好的解释。

看看这个非常简单的程序:

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”部分出现故障。这是怎么回事?

最佳答案

嗯,这是基础知识。段错误意味着您正在使用您无权访问的内存。

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 中的指针和内存缺乏了解造成的。

祝你好运

关于C - fgets 在使用 char 数组时神秘地导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39323588/

相关文章:

C:(工作但未按预期进行)我的确定方法是编辑提供的矩阵(作为参数)但我只是希望它提供确定的

c++ - 设置声明值时调用函数

iphone - Signal 11,iPhone 应用程序退出时出现段错误

c - 使用 fgets( ) - 内存效率最高的方法

正确地将文件内容按行存储到数组中,稍后打印数组内容

c - 错误: incompatible integer to pointer conversion assigning to 'string' (aka 'char *' ) from 'int'

C 列表段错误

C: fgetc 给出段错误

C - 有没有办法用 'Enter' 以外的键终止字符串输入?

如果参数包含等号,CGI 脚本不会接收参数