c - 在 C 中释放双指针时出错

标签 c memory free genetic-algorithm

我正在为遗传算法编写代码,但我无法释放未使用的内存。这是我的 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]);发生时,我收到以下错误:

检测到堆损坏:在正常 block 之后(#99)。 CRT 检测到应用程序在堆缓冲区结束后写入内存。

最佳答案

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;

你在每个字符串 szChromosomes[i] 的末尾插入一个 '\0' 但只使用长度为 d->m_iBitsPChromosome 的 malloc

所以你试图在内存中写得太远。要更改它,只需将您的第二个 malloc 更改为:

szChromosomes[i] = (char*)malloc((d->m_iBitsPChromosome + 1) * sizeof(char));

关于c - 在 C 中释放双指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15116864/

相关文章:

c# - SendMessage 的对话十进制值到十六进制值出现问题

C - 释放堆栈内数组内的特定结构

c++ - 如何使用 double 更安全和精确?

c - 如何将 memcpy 转换为 memcpy_s?

c - 了解嵌套 for 循环的逻辑

memory - 对内存映射感到困惑

C - 释放指向指针的指针

c - 释放传递给分配它的函数的指针

c - 关于c中的二进制搜索算法的问题

cuda线程索引