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

时间:2013-01-15 14:54:42

标签: 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.

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

5 个答案:

答案 0 :(得分:5)

weather是首次在以下电话中使用时的char*

gets(weather);

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

char weather[128];

在随后的write()调用中,使用strlen(weather)代替sizeof(weather)仅编写已读取的字符(并正确处理weather为{的情况{1}}而不是char*)。

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

答案 1 :(得分:2)

您永远不会为指针分配任何内存:char *weather;

来自man page

  

char * gets(char * s);
  gets()从stdin读取一行到s指向的缓冲区,直到终止换行符或EOF,

所以你需要一个缓冲区来存储它:

char weather[10];

char *weather;
weather = malloc(10);
如果10足够,

会这样做。这又从手册页引出了另一点:

  

永远不要使用gets()。因为在不事先知道数据的情况下无法判断get()将读取多少个字符,并且因为gets()将继续存储超出缓冲区末尾的字符,所以使用它是非常危险的。它已被用来打破计算机安全。请改用fgets()。

例如:

fgets (weather, 10 , stdin);

答案 2 :(得分:2)

问题在于这两行:

char *weather;

gets(weather);

第一个声明weather是一个指针,但它未被初始化(即指向一个看似随机的位置)。第二行写入weather指向的内容,这意味着您写入一些随机位置。

weather声明为数组,然后改为使用fgets

char weather[64];

/* ... */

fgets(weather, sizeof(weather), stdin);

答案 3 :(得分:0)

你会在指向未分配内存的指针上获取(天气)。

答案 4 :(得分:0)

char *weather;

然后

gets(weather);

导致分段错误。 weather应该指向一个内存空间:

  • staic

    char weather[100]

  • 或动态

    char *weather = malloc(100*sizeof(char));

相关问题