Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault before first line of code

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?

like image 211
Bertholt Stutley Johnson Avatar asked Nov 21 '12 03:11

Bertholt Stutley Johnson


2 Answers

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.

like image 135
Sergey Kalinichenko Avatar answered Nov 09 '22 03:11

Sergey Kalinichenko


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.

like image 43
dst2 Avatar answered Nov 09 '22 04:11

dst2