创建文件时出现分段错误11

tom*_*lik 0 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;
}**
Run Code Online (Sandbox Code Playgroud)

错误是分段错误11.

先感谢您!(抱歉我的英文,真的很糟糕^^)

hmj*_*mjd 5

weather在下次char*调用中首次使用时是一个单元化的:

gets(weather);
Run Code Online (Sandbox Code Playgroud)

意思gets()是试图写入内存不应该,导致分段错误.为内存分配内存weather或使用数组:

char weather[128];
Run Code Online (Sandbox Code Playgroud)

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

另外,请参阅为什么获取功能如此危险以至于不应该使用它?.使用fgets()或可能scanf()使用长度说明符.