I am passing a txt file as command line argument and displaying it contents to the stdout. I want to create 5 integer variables (n,a,b,i,temp) at the start of the program. But the program is giving me a segfault once I declare more than 2 integers. If I comment out the third int declaration (int b), the program is running fine. Also, I am running on ubuntu.
main(int argc, char *argv[]){
int n;
int a;
int b;
// int i;
// int temp;
char *s;
if(argc!=2){
printf("not enough arguments provided!!\n");
exit(-1);
}
FILE *fp = fopen(argv[1],"r");
while((s=fgets(s,5,fp))!=NULL){
n = atoi(s);
printf("%d",n);
}
fclose(fp);
}
Your
fgets(s,5,fp)reads into an uninitialized pointer. You have to allocate storage which you place the read data into.Change
char *s;tochar s[5];Edit: Also change your while loop condition:
You should also check whether fopen() succeeds or fails.