strncmp() 関数でセグメンテーション違反 11 が発生しました。バグの場所はわかっていましたが、何が原因なのかわかりません。これが私が解決しようとしているものです。大量の単語を含む txt ファイルを入力します。次に、各単語の頻度を計算し、単語を並べ替える必要があります。最後に、ソートされた単語を頻度とともに出力します。Cプログラムなので、リンクリストを使用して単語と頻度を保存します。リンクされたリストに単語を追加することと、各単語の頻度をカウントすることの両方がうまく機能します。バグは、単語のソートに使用するクイックソートで発生します。私のクイックソート:
struct node *quick_sort(struct node *head, int l, int r){
int i, j;
int jval;
int pivot;
int min;
char* test1;
char* test2;
i = l + 1;
if (l + 1 < r) {
test1 = get_char(head, l);
pivot = get_freq(head, l);
for (j = l + 1; j <= r; j++) {
jval = get_freq(head, j);
test2 = get_char(head, j);
printf("test 1: %s test 2: %s\n",test1,test2);
min = strlen(test1) < strlen(test2) ? strlen(test1) : strlen(test2);
printf("Length 1 :%ld Length 2: %ld Max is: %d\n",strlen(test1),strlen(test2), min);
// HERE is where the bug is
if (strncmp(test2,test1,min)<0 && jval != -1) {
swap(head, i, j);
i++;
}
}
swap(head, i - 1, l);
quick_sort(head, l, i);
quick_sort(head, i, r);
}
return head;
}
その他の関連機能:
int get_freq(struct node *head, int l){
while(head && l) {
head = head->next;
l--;
}
if (head != NULL)
return head->freq;
else
return -1;
}
void swap(struct node *head, int i, int j){
struct node *tmp = head;
int tmpival;
int tmpjval;
char* tmpiStr;
char* tmpjStr;
int ti = i;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmpival = tmp->freq;
tmpiStr = tmp->str;
tmp = head;
while(tmp && j) {
j--;
tmp = tmp->next;
}
tmpjval = tmp->freq;
tmpjStr = tmp->str;
tmp->freq = tmpival;
tmp->str = tmpiStr;
tmp = head;
i = ti;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmp->freq = tmpjval;
tmp->str = tmpjStr;
}
char* get_char(struct node *head, int l){
char* res;
while(head && l) {
head = head->next;
l--;
}
if (head != NULL){
char * arr = head->str;
return arr;
}
else
return res;
}
strncmp() の分数を変更すると、プログラムが動作することがあります。何が悪いのかわかりません。前もって感謝します。