Qsort导致内存丢失

时间:2017-12-25 02:43:34

标签: c valgrind qsort

我的程序涉及合并两个定义为:

的个体数组(称为人口)
struct individual {
    struct node *genome; // binary tree
    double fitness; // less or equal to zero
};

它还涉及使用这些功能对每个群体进行排序:

void sort_population(struct individual **population) {
    int pop_size = 100;
    qsort(population, pop_size, sizeof(struct individual *), fitness_comp);
}

int fitness_comp(const void *elem1, const void *elem2) {
    struct individual *i1 = *(struct individual **)elem1;
    struct individual *i2 = *(struct individual **)elem2;

    if (i1->fitness < i2->fitness) return 1;
    if (i1->fitness > i2->fitness) return -1;

    return 0;
}

问题在于,在调用sort_population之后,程序会丢失对人口中每个人的跟踪。

受影响的功能特别取代了一个人口中最差的人口。这是功能:

struct individual **generational_replacement(struct individual **new_population, 
       int size, struct individual **old_population) {

    int elite_size = 2;

    // These next two lines cause the errors
    sort_population(new_population);
    sort_population(old_population);

    for (int i = 0; i < elite_size; i++) {
        if (old_population[i]->fitness > new_population[size - i - 1]->fitness) {
            free_individual(new_population[size - i - 1]); // free the ones that are not used
            new_population[size - i - 1] = old_population[i];
        }
    }

    return new_population;
}

我知道对sort_population的调用导致了这个问题,因为程序正确执行并且如果调用被注释掉,则会减少内存丢失。具体来说,valgrind检测到更多的内存泄漏,并且当没有注释掉调用时,程序输出的结果不正确。

造成这种情况的原因是什么?

指向github的链接是:https://github.com/dyingpie1/pony_gp_c

1 个答案:

答案 0 :(得分:1)

在将sort_population的第一个参数更改为单个指针后,您可以尝试执行吗?如下所示。

void sort_population(struct individual *population) {
    int pop_size = 100;
    qsort(population, pop_size, sizeof(struct individual *), fitness_comp);
}