c - 在C中使用插入排序对字符串进行排序 - 段错误

标签 c pointers memory segmentation-fault

我正在尝试调整我的数字排序插入排序代码来对字符串输入文件进行排序,例如:

thickness
combed
revocable
escorted

但是,当尝试运行以下命令时,我遇到了段错误(核心转储):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRING_LEN  80
#define ARRAY_LEN   10000

void insertion_sort(char **a, int n) {
    int i;
    int j;
    char *key;

    for (i = 1; i < n; i++) {
        key = a[i];
        j = i - 1;

        while (strcmp(key, a[j]) == -1 && j >= 0) {
            a[j + 1] = a[j];
            j = j - 1;
        }
        a[j + 1] = key; 
    }
}

void *emalloc(size_t s) {
    void *result = malloc(s);
    if (NULL == result) {
        fprintf(stderr, "Memory allocation failed!\n");
        exit(EXIT_FAILURE);
    }
    return result;
}

int main(void) {
    int j;
    int num_words = 0;
    char word[STRING_LEN];
    char *wordlist[ARRAY_LEN];

    while (num_words < ARRAY_LEN && 1 == scanf("%79s", word)) {
        wordlist[num_words] = emalloc((strlen(word) + 1) * sizeof wordlist[0][0]);
        strcpy(wordlist[num_words], word);
        num_words++;    
    }

    insertion_sort(wordlist, num_words);

    for (j = 0; j < num_words; j++) {
        printf("%s\n", wordlist[j]);
    }

    return EXIT_SUCCESS;
}

我发现将 while 条件更改为 > 0 而不是 >= 0

while (strcmp(key, a[j]) == -1 && j > 0)

它对除第一个字符串之外的所有内容进行排序,因为当 j0 并且未进入循环时,输出为:

thickness
combed
escorted
revocable

我是 C 新手,我认为这与访问尚未分配的内存有关,但我很难找到位置。

最佳答案

您的循环测试不正确:

while(strcmp(key,a[j]) == -1 && j>=0){

您应该在使用索引j之前检查它,并且不应依赖strcmp()返回-1 对于 key 小于 a[j]strcmp() 仅指定为在这种情况下返回负值。

while (j >= 0 && strcmp(key, a[j]) < 0) {

关于c - 在C中使用插入排序对字符串进行排序 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648965/

相关文章:

c - 在 C 中使用 free 释放非字符指针

c++ - 为什么这个 C++ 'new' 运算符的实现有效?

c - 示例 : scanf and char errors

c - 使用英特尔编译器 (icc) 的四精度数字

c - 如果将 Unicode 数据解析为多字节,程序会崩溃吗?

c - 如何在C中检索字符串的多个子字符串并将它们写入一个字符串?

c - 指针取消引用如何工作?

c# - 有没有一种方法可以检查 Android/Xamarin/c#/net 中使用的内存、空闲内存甚至内存泄漏

Java map 存储百万条记录

c - 有没有办法在 Visual Studio 中为整个解决方案或项目将 EOL 设置为 LF?