我正在做一个简单的项目,但我遇到了一个错误。我在 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)
来仅写入被写入的字符读取(并正确处理 weather
是 char*
而不是 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/