I’m working on an easy project but I’ve encountered an error. I’m coding in Unix and executing the code with the terminal.
#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;
}**
The error is a segmentation fault 11.
Thank you in advance!
(and sorry for my English, it’s really bad ^^)
The problem is these two lines:
and
The first declares
weatherto be a pointer, but it’s left uninitialized (i.e. points to a seemingly random location). The second line writes to whatweatherpoints to, which means you write to some random location.Declare
weatheras an array, and usefgetsinstead: