簡體   English   中英

strncmp()在我的快速排序c編程中給出了Segmentation Fault 11

[英]strncmp() give Segmentation Fault 11 in my quick sort c programming

我的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()中的min數,有時該程序會起作用。 我不知道錯在哪里。 提前致謝。

您永遠不會在此行上分配給在get_char函數中聲明的變量

char* res;

當程序訪問未分配的內存時,通常會調用Segmentation fault 11錯誤。 在您的情況下,您可能正在嘗試比較字符串和內存中的一些隨機位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM