1

遺伝的アルゴリズムのコードを書いていますが、未使用のメモリを解放できない状態で立ち往生しています。これは私の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は、ヒープバッファの終了後にアプリケーションがメモリに書き込んだことを検出しました。

4

2 に答える 2

2
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;

各文字列の末尾に「\0」を挿入しますszChromosomes[i]が、d->m_iBitsPChromosomeの長さのmallocのみを使用します

そのため、メモリに書きすぎてしまいます。これを変更するには、2番目のmallocを次のように変更します。

szChromosomes[i] = (char*)malloc((d->m_iBitsPChromosome + 1) * sizeof(char));
于 2013-02-27T16:22:18.603 に答える
1
szChromosomes[i][j] = '\0';

this line writes to memory you do not own.

For eg. take this example

char * p;
p = malloc(2);
p[0] = 'a';
p[1] = 'b';

You should not be doing

p[2] = '\0'

after this because you have allocated only 2 bytes, but you are writing to 3 bytes.

You can fix this 2 ways

  1. Do you need the '\0'. Unless, you are going to use one of the functions from <string.h> which expects a '\0' to check the end, you need to terminate it by '\0'. In your own code which traverses the array, you can traverse using a for loop which ends at ctr < d->m_iBitsPChromosome.

  2. Or you can allocate malloc(d->m_iBitsPChromosome + 1)

于 2013-02-27T16:21:17.997 に答える