繁体   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