I'm learning C and I moved recently from Windows to Linux. I was coding a simple program, getting a recurrent error: Segmentation fault (core dumped). I've analyzed all the code and realized that the error is caused by this function that reads data from a file:
FILE *f_out = fopen("sysdata.txt","r ");
char line[30];
while (fgets(line, sizeof(line), f_out) != NULL)
{
count ;
if (count == 0)
{
if (line != "1") {first_project = true;}
else {first_project = false;}
}
}
I've searched a bit online: i've not understand the error very well (i'm at the basics of c learning) but i have found this. It's the only tutorial that can help me, but i get an error at the last command: running sudo dpkg -l | grep ^..r | apt-get purge. The error is here.
I searched online but nothing. Anyone knows how to solve this problem or how to make work my app without segmentation fault?
CodePudding user response:
There are several issues with the code presented, but if your segfault arises there then the only plausible explanation is that the fopen()
is failing, probably because there is no file with the designated name in the program's working directory. fopen()
returns a null pointer on failure, and it is the program's responsibility to check for that before attempting to use the result with I/O functions. If you do try to use a null pointer with fgets()
then a segfault is a likely outcome.
That is approximately as true on Windows as on Linux, though I believe the Windows terminology differs a bit. However, it may be that your unfamiliarity with Linux is contributing to a misunderstanding of what the program's working directory is for your test runs.
CodePudding user response:
A segmentation fault, commonly known as segfault, occurs when your program wants to access a memory address outside of your program's allocated memory region. It means that you can get a segfault by for example reading outside array's bounderies.
However segfault here is not a direct cause of the problems. The segfault occurs internally within the fgets function. This is because the file handler might be NULL, meaning that it didn't open succesfully. What your code needs is a small check to ensure the f_out is not NULL.
if (f_out == NULL)
{
puts("file could not be opened");
return 1;
}
Add this just after you open the file and you should be fine.