我正在为遗传算法编写代码,但我被困在无法释放未使用内存的地步。这是我的 main() 代码:
szChromosomes = initial_population(&data[0]);
while (iCurrentGen <= data->m_iMaxGenerations)
{
arrfSelectedChromosomes = selection(&data[0], szChromosomes);
iSelectedLen = order_descending_grid(arrfSelectedChromosomes);
szAuxGen = crossover(&data[0], arrfSelectedChromosomes, szChromosomes);
free_generation(&data[0], szChromosomes);//Error line
szChromosomes = szAuxGen;
szAuxGen = NULL;
}
initial_population(&data[0]) 创建 szChromosomes 数组(我稍后尝试释放),如下所示:
char** initial_population(struct INPUT_DATA* d)
{
int i, j = 0;
float fMember = 0.0;
char** szChromosomes = (char**)malloc(d->m_iPopulationSize * sizeof(char*));
srand(time(NULL));
for (i = 0; i < d->m_iPopulationSize; ++i)
{
szChromosomes[i] = (char*)malloc(d->m_iBitsPChromosome * sizeof(char));
for (j = 0; j < d->m_iBitsPChromosome; ++j)
{
szChromosomes[i][j] = rand_1_0(0.0, 1.0) == 1? '1' : '0';
}
szChromosomes[i][j] = '\0';
}
return szChromosomes;
}
当我调用 free_generation 函数时,会执行下面的 For 循环:
int i;
for (i = 0; i < d->m_iPopulationSize; ++i)
{
free(szChromosomes[i]);
}
free(szChromosomes);
szChromosomes = NULL;
当第一次调用 free(szChromosomes[i]); 发生,我收到以下错误:
检测到堆损坏:在正常块 (#99) 之后。CRT 检测到应用程序在堆缓冲区结束后写入内存。