c - 创建文件时出现段错误 11

标签 c unix segmentation-fault

我正在做一个简单的项目,但我遇到了一个错误。我在 Unix 中编码并使用终端执行代码。

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int atis;
    char *weather;

    //Création du fichier ATIS
    if((atis = creat("atis", 0666)) == -1)
    {
        printf("Error while creating the ATIS file\n");
        exit(-1);
    }

    //Ouverture du fichier ATIS
    if((atis = open("atis", 0666)) == -1)
    {
        printf("Permission denied\n");
        exit(-1);
    }

    //Mise à jour du fichier ATIS
    printf("OK or KO for a take-off? ");
    gets(weather);
    if(write(atis, weather, sizeof(weather))==-1)
    {
        printf("Write error\n");
        exit(-1);
    }


    close(atis);
    return 0;
}**

错误是段错误11。

提前致谢! (对不起我的英语,真的很糟糕^^)

最佳答案

weather 是一个单元化的 char*,当第一次在以下调用中使用时:

gets(weather);

意味着 gets() 将尝试写入不应该写入的内存,从而导致段错误。为 weather 分配内存或使用数组:

char weather[128];

在随后对 write() 的调用中,使用 strlen(weather) 而不是 sizeof(weather) 来仅写入被写入的字符读取(并正确处理 weatherchar* 而不是 char[] 的情况)。

此外,请参阅 Why is the gets function so dangerous that it should not be used? .使用 fgets()或者可能 scanf()用长度说明符代替。

关于c - 创建文件时出现段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340346/

相关文章:

c++ - 这在内部是如何工作的 int const iVal = 5; (int&)iVal = 10;

c - deallocuvm 在 Xv6 中如何工作?

regex - 匹配特定模式后在数字之间插入空格

c - 如何摆脱 NULL 段错误?

c - 段错误字符** C

c - 将数据写入文件时如何生成信号?

c - 使用 setuid 降低到较低权限级别的正确方法是什么?

linux - 如何在 Bash 中给定的实际运行时间后终止进程?

c++ - 大小为 500000 的部分排序数组的快速排序段错误

c - 如何在 C 二进制文件中嵌入 Lua 脚本?