user7028056 user7028056 - 1 month ago 13
C Question

C segmentation fault(core dumped)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int Search_in_File(char *fname,char *str){
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
if((fp = fopen(fname, "r")) == NULL)
return(-1);

while(fgets(temp, 512, fp) != NULL){
if((strstr(temp, str)) != NULL){
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0){
printf("\nSorry, couldn't find a match.\n");
}
if(fp)
fclose(fp);
return(0);
}
void main(){
char file_name[15];
char *fname;
*fname=file_name[15];
char *str;
char string_to_be_searched[15];
*str=string_to_be_searched[15];
int result, errno;
printf("Enter The File Name :");
scanf("%s",fname);
printf("Enter The String To Be Searched :");
scanf("%s",str);
result = Search_in_File(fname , str);
if(result==-1){
perror("Error");
printf("Error number = %d\n", errno);
exit(1);
}
}


I wrote this little program to search string from a file but it shows segmentation fault(core dumped) in gcc Linux
What is this error for ? How can I fix it ?

Answer
char *fname; 
*fname=file_name[15]; 

Think about what that code does. When you assign value to *fname, which memory does fname point to?

The answer is: fname is uninitialized pointer, which can point to any random location in memory. Most likely it contains 0, so trying to dereference it results in immediate SIGSEGV (but this is not guaranteed).

You should also learn to use a debugger, which would point you straight at the problem.

Comments