在C中释放双指针时出错

在C中释放双指针时出错,c,memory,free,genetic-algorithm,C,Memory,Free,Genetic Algorithm,我正在为一个遗传算法编写代码,我被困在一个无法释放未使用内存的地方。这是我的main()代码: sz染色体=初始_总体(&data[0]); while(iCurrentGen m_iMaxGenerations) { arrfselectedchromes=选择(&data[0],szchromes); iSelectedLen=顺序下降网格(arrfselectedchromes); szAuxGen=交叉(&数据[0],arrfselected染色体,szAuxGen染色体); 自由_生成

我正在为一个遗传算法编写代码,我被困在一个无法释放未使用内存的地方。这是我的main()代码:

sz染色体=初始_总体(&data[0]);
while(iCurrentGen m_iMaxGenerations)
{
arrfselectedchromes=选择(&data[0],szchromes);
iSelectedLen=顺序下降网格(arrfselectedchromes);
szAuxGen=交叉(&数据[0],arrfselected染色体,szAuxGen染色体);
自由_生成(&数据[0],sz);//错误行
szAuxGen;
szAuxGen=NULL;
}
初始_population(&data[0])创建sz染色体数组(稍后我将尝试释放该数组),如下所示:

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;
char**初始填充(结构输入数据*d)
{
int i,j=0;
浮动成员=0.0;
char**sz染色体=(char**)malloc(d->m_i种群大小*大小(char*);
srand(时间(空));
对于(i=0;im_i人口规模;++i)
{
sz染色体[i]=(char*)malloc(d->m_iBitsPChromosome*sizeof(char));
对于(j=0;jm_iBitsPChromosome;++j)
{
sz染色体[i][j]=rand_1_0(0.0,1.0)==1?'1':'0';
}
sz[i][j]='\0';
}
回归分析;
}

调用free_generation函数时,执行下面的For循环:

    int i;

for (i = 0; i < d->m_iPopulationSize; ++i)
{
    free(szChromosomes[i]);
}

free(szChromosomes);
szChromosomes = NULL;
inti;
对于(i=0;im_i人口规模;++i)
{
自由(sz[i]);
}
游离(sz);
sz=NULL;
当第一次调用free(szy[i]);发生时,我得到以下错误:

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

szChromosomes[i][j] = '\0';
此行将写入您不拥有的内存

举个例子

char * p;
p = malloc(2);
p[0] = 'a';
p[1] = 'b';
你不应该这样做

p[2] = '\0'
之后,因为您只分配了2个字节,但您正在写入3个字节

你可以用两种方法解决这个问题

  • 您需要“\0”吗。除非您打算使用
    中的一个函数,该函数需要一个“\0”来检查结束,否则您需要在“\0”之前终止它。在您自己的遍历数组的代码中,您可以使用以
    ctrm_iBitsPChromosome
    结尾的for循环进行遍历

  • 或者您可以分配
    malloc(d->m_iBitsPChromosome+1)


  • 尝试
    (char*)malloc(d->m_iBitsPChromosome+1)。最后需要为
    '\0'
    添加一个额外字符。与
    sizeof(char)
    相乘是多余的,因为标准将
    char
    定义为大小为1字节。这就是问题所在\0字符需要额外的字节!真不敢相信我竟然错过了这么多!谢谢你们!
    p[2] = '\0'
    
    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] = (char*)malloc((d->m_iBitsPChromosome + 1) * sizeof(char));