C - Segmentation Fault Somewhere -
i keep getting segmentation fault. figured out happens between these 2 lines:
printf("%s - file exists!\n", file_name); printf("inforloop");
but i'm unsure why segmentation fault keeps occuring. entire code:
#include<stdio.h> #include<unistd.h> #include<string.h> file *fp; char err_message[128], file_name[128]; int main(int argc, char *argv[]) { if(argc <= 2) { printf("error : usage %s <file name>\n", argv[0]); return 1; } int = 1; for(i; i< argc; i++) { strcpy(file_name, argv[i]); if ((access(file_name, f_ok)) != -1) { printf("begining of loop\n"); printf("%s - file exists!\n", file_name); printf("inforloop"); fclose(fp); } else { sprintf(err_message, "open %s", file_name); perror(err_message); } } return 0; }
outcome:
1 begining of loop date.txt - file exists! segmentation fault (core dumped)
you're fclose
ing fp
, have never fopen
ed, or initialized.
the output cut off before printing inforloop
because standard output line-buffered, , there no line feed after inforloop
.
Comments
Post a Comment