我的程序涉及合并两个个体数组(称为人口),定义如下:
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
你可以尝试在将sort_population的第一个参数更改为单个指针后执行。如下所示。
void sort_population(struct individual *population) {
int pop_size = 100;
qsort(population, pop_size, sizeof(struct individual *), fitness_comp);
}