在分配的内存中使用qsort后,为什么自由功能会崩溃?

时间:2019-06-16 00:08:36

标签: c crash malloc free qsort

我正在使用malloc为字符串分配内存,然后在该内存上执行qsort以对字符串的字符进行排序。

我多次执行qsort,每次都将新值复制到分配的内存中。

此后,我尝试free内存但它崩溃了

如果我评论qsort

,它不会崩溃
/**
 * Iterates over b finding permutations of s
 *
 * @param s smaller string
 * @param b bigger string
 * @param locations array for the result
 * @return number of locations
 */
int substring_permutations(const char *s, const char *b, int *locations) {
    int s_len = (int) strlen(s);

    char *sorted_sub_b = malloc((s_len + 1) * sizeof(char));
    sorted_sub_b[s_len] = '\0';

    char *sorted_s = malloc((s_len + 1) * sizeof(char));
    sorted_s[s_len] = '\0';
    sort_string(s, s_len, sorted_s);

    int l = 0;
    for (int i = 0; i < strlen(b) - s_len + 1; i++) {
        sort_string(b + i, s_len, sorted_sub_b);

        if (strcmp(sorted_s, sorted_sub_b) == 0) {
            locations[l++] = i;
        }
    }

    free(sorted_s);
    free(sorted_sub_b); // Why does this crash?
    return l;
}

void sort_string(const char *s, int s_len, char *sorted_s) {
    memcpy(sorted_s, s, s_len * sizeof(char));
    qsort(sorted_s, s_len * sizeof(char), sizeof(char), chrcmp);
}

int chrcmp(const void *a, const void *b) {
    return *(char *) a - *(char *) b;
}

执行第二个free

时崩溃
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

编辑:添加呼叫代码


int main() {
    const char *s = "abbc";
    const char *b = "cbabadcbbabbcbabaabccbabc";

    printf("%s\n", s);
    printf("%s\n", b);

    size_t s_len = strlen(s);
    size_t b_len = strlen(b);
    int *locations = malloc((b_len + 1 - s_len) * sizeof(char));

    int permutations = substring_permutations(s, b, locations);

    for (int i = 0; i < permutations; i++) {
        int location = locations[i];
        printf("%d ", location);
        print_chars(b + location, s_len);
        printf("\n");
    }

    free(locations);

    return 0;
}

void print_chars(const char *c, size_t size) {
    for (int i = 0; i < size; i++) {
        printf("%c", c[i]);
    }
}

编辑2 :我现在看到了问题,它在调用代码中:

我有

    int *locations = malloc((b_len + 1 - s_len) * sizeof(char));

代替

    int *locations = malloc((b_len + 1 - s_len) * sizeof(int));

谢谢@ user5329483

0 个答案:

没有答案