Segmentation fault before first line of code - c

I am working on a simple C program to open a file and read some data from it. There are no compile errors, but when I run the program on a certain file, I get a "Segmentation Fault: code dumped" error. I inserted a print statement at the very top of my code, and it does not get run. Is it possible to get a segmentation fault when you haven't done anything yet?
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s", "Made it to here!");
FILE *fp;
char input[100];
fp = fopen(argv[1], "r+b");
fgets(input, sizeof(input), fp);
printf("%s", input);
fclose(fp);
return(0);
}
This works when I run it on the text version of itself, it prints out the first line. However, when I run it on another file, texttest.vmf, I get the segmentation fault and the first print doesn't execute. VMFs are Valve Map Files, but they're in standard text format. This file is about 3.7 KB large. Any ideas?

It is not necessary that your code fails before printf: the call to printf may have succeeded, but because the output to console is buffered, the program may have crashed before the output has been written to the screen.
Adding \n to the output string causes console buffer flush. If you are looking to debug by printfs, you should always add \n to the end of your format string.

Your fopen call is likely failing. Try checking the return value before you attempt to use fp:
FILE *fp;
char input[100];
if((fp = fopen(argv[1], "r+b") == NULL) {
fprintf(stderr, "ERROR: Cannot open file.\n");
return 1;
}
Make sure to add #include <stdlib.h> for use of the NULL macro.

Related

Why do I get a segmentation fault when getting file name using user input?

I will strip the code down to only the parts I am having trouble with.
When I do the following, the code works
int main() {
FILE * fptr1 = fopen("in.txt", "r");
fread(data, sizeof(char), size, fptr1);
.
.
.
FILE * fptr2 = fopen("out.txt", "w");
fwrite(data, sizeof(char), size, fptr2);
fclose(fptr2);
}
But when I use fgets to get the input and output file name using fgets or scanf, I get a segmentation fault.
int main() {
char inputfile[100];
char outputfile[100];
printf("name of input file: \n");
fgets(inputfile, 100, stdin);
printf("name of output file: \n");
fgets(outputfile, 100, stdin);
.
.
.
}
I have been playing around with this for a while. I tried using scanf and tried changing the allocated sizes for inputfile and outputfile but I keep getting:
Segmentation fault (core dumped)
With fgets(), the resulting filenames inputfile and outputfile contain the terminating newline characters. It causes the following fopen() failed and returned NULL.
However, you didn't check for nullity of FILE*'s before calling fread() or fwrite(), and this led to segmentation fault.
A string inputted using fgets() contains a terminating '\n', which is usually unexpected. Although this won't cause a segfault directly, it may cause fopen() to return NULL, since it cannot find that file. Trying reading data from a null file pointer will cause a segfault.
Add
if(fptr1 == 0)
{
perror("fopen()");
exit(EXIT_FAILURE);
}
after your fopen() statements.

How to read text file in C?

I'm trying to read a txt file containing strings of 1s and 0s and print it out in the manner below. I tried my code a couple of months ago and it worked fine in reading the text file. Now when I tried it, it outputs something really strange. Also I tried changing the directory of the file to a non-existant file but it still outputs the same thing when it should've quit the program immediately. Please help!
The content of txt file:-
10000001
01110111
01111111
01111010
01111010
01110111
Expected output:-
data_in<=24'b10000001;
#10000;
Real output:-
data_in<=24'b(some weird symbol that changes everytime I recompile);
#10000;
My code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i, j;
j = 0;
char words[50];
FILE *fp;
fp = fopen (argv[1], "r");
if (fp == NULL) {
printf ("Can't open file\n");
}
while (feof (fp) == 0) {
fscanf (fp, "%s", words);
printf ("data_in<=24'b%s\n", words);
printf ("#10000\n");
}
fclose (fp);
system ("PAUSE");
return 0;
}
The input argument is the following:-
"C:\Users\Beanz\Documents\MATLAB\football frame\frame1.txt"
Read each line one by one with getline(3) -if available- or with fgets (you'll then need a large enough line buffer, at least 256 bytes), then parse each line buffer appropriately, using sscanf (the %n might be useful, and you should test the scanned item count result of sscanf) or other functions (e.g. strtok, strtol, etc...)
Remember that 'feof()' is only set AFTER trying to read PAST the end of the file, not when at the end of the file.
So the final iteration through the loop will try to read/process data that contains trash or prior contents.
Always check the returned value from 'fscanf()' before trying to use the associated data.
strongly suggest
eliminate the call to feof() and use the fscanf() to control the loop

C segmention fault when opening file

This seems to be a really simple one, but I can't figure it out after not touching C programming in four years.
I was trying to open a file in main()
int main(int argc, const char * argv[])
{
FILE * fp = fopen("data.txt","r");
...
return(0)
}
The program compiled, but when I tried to run it in gdb, the following error occurs.
Program received signal SIGSEGV, Segmentation fault.
0x00000000004016c6 in main ()
when the program is trying to open the file "data.txt". What could cause the error? Thanks!
I suspect your error lies in this bit of code:
...
In other words, there's nothing in the other code shown that appears to be wrong.
The most likely case is that the file doesn't exist, or it doesn't exist in the directory where the program is running (which, if you're in an IDE, usually turns out to be somewhere other than you think it is).
And, in that case, you're getting NULL from the fopen, then later using it, something like:
FILE *fp = fopen ("no_such_file.txt", "r");
int ch = fgetc (fp);
You should generally check return values from all functions that use them to indicate success or failure:
#include <stdio.h>
int main (void) {
FILE *fp = fopen ("no_such_file.txt", "r");
if (fp == NULL) {
perror ("Opening no_such_file.txt");
return 1;
}
// You can use fp here.
puts ("It worked.");
fclose (fp);
return 0;
}
What could cause the error?
The most likely cause of the error is that the file data.txt could not be opened (e.g. because it doesn't exist, or it's not in the current directory, or your program doesn't have permission to read it). That will cause fopen() to return NULL. Then if your code (in the ... section) tries to call fread() or fgets() or whatever and passes in the NULL pointer, that will cause a crash. You need to check the value returned by fopen() to make sure it is non-NULL before trying to use it.

reading data from a file into an array error in C

I am trying to read from a file specified in a command prompt through terminal using the line program < file.txt and then print it again to check it works. I get the error Segmentation fault: 11, I'm not sure if my file is opening correctly in my program.
This is the code so far:
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
Any help or feedback would be greatly appreciated.
You should execute your program like
./program file.txt
I'm not sure if my file is opening correctly in my program
Then you should really test for it, you are getting a segfault because fopen is returning NULL.
#include <stdio.h>
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
if (!fp) {
printf("Invalid file name \n");
return -1;
}
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
fopen is NULL because you are invoking the program in the wrong manner, < and > are a re-directions which can be useful but is not what you are trying to do in this case, correct way to invoke it is to simply pass it the arguments directly.
./program input.file
Yeah, either:
1) check the way you're invoking it, i.e,
check if the 'program' is an executable file, you can make it executable using chmod command in linux
check if the path to 'program' or 'file.txt' is correct
2) (I'm not sure of this): check if the content of 'file.txt' is of the right content. (I don't think it should affect to the extent that it causes a segmentation fault, but still, check it.)

Read text into C. Get a bad exec error

Trying to learn C. Want to read the first line of a text file, my code is:
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
return 0;
}
I'm doing this in xCode. I get a exc bad access error.
test.txt definitely exists. It has one line that says "this is a text file"
try this after fopen() call:
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
and add the headers:
#include <errno.h>
#include <string.h>
The code looks fine, so my guess is that the program is not run in the same working directory as the file. Try placing the file in, say, /tmp/test.txt and use absolute path in fopen.
You don't check if the FILE is NULL. It may not be opened for a several reasons.

Resources