I just started to learn C and need some helps. I already compiled my code and fixed all warnings that occur. However, when I run my program it says 'Segmentation Fault' and this is my code.
#include <stdio.h>
#include <string.h>
char *sorting(char word[51], int n)
{
for (int i = 0; i < n; i ) {
for (int j = i 1; j < n; j ) {
if (word[i] > word[j]) {
char temp = word[i];
word[i] = word[j];
word[j] = temp;
}
}
}
return word;
}
From above, I just sort the word in order to use in strcmp
.
First I will read file that contains jumbled words. Next read dictionary's file. Then I will check whether two words are the same.
int main(int argc, char **dict, char **jambles)
{
const char *j = jambles[1];
FILE *jambles_file = fopen(j, "r");
char jambles_words[51];
while (fgets(jambles_words, sizeof(jambles_words), jambles_file)) {
int count = 0;
const char *d = dict[1];
FILE *dict_file = fopen(d ,"r");
char dict_words[51];
printf("%s", jambles_words);
while (fgets(dict_words, sizeof(dict_words), dict_file)) {
int length_jambles = strlen(jambles_words);
int length_dict = strlen(dict_words);
char *j_ = jambles_words;
char *d_ = dict_words;
const char *sort_jambles = sorting(j_, length_jambles);
const char *sort_dict = sorting(d_, length_dict);
if (length_jambles == length_dict) {
int compare = strcmp(sort_jambles, sort_dict);
if (compare == 0) {
printf("%s", dict_words);
count ;
}
}
else if (count == 0) {
printf("NO MACTHES");
}
}
printf("\n");
}
return 0;
}
I still don't know what are the mistakes of my code even I already search on the internet for the causes of Segmentation Fault.
CodePudding user response:
I suspect the root cause is that you misunderstand how command-line arguments are passed to C programs. When you run ./a.out foo bar
and it calls into int main(int argc, char **argv, char **envp)
, "foo"
will be in argv[1]
and "bar"
will be in argv[2]
. envp
will just contain environment variables like "TERM=xterm"
and "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
. You appear to think that "bar"
will instead end up in envp[1]
, which is incorrect.
The more immediate cause is likely that because of the above, your call to fopen
is failing due to a file called "TERM=xterm"
or something not existing, and so returning NULL
, which you then pass to fgets
blindly. In general, it's Undefined Behavior to pass null pointers to any standard library function that doesn't specifically say what doing so will do.