Search code examples
c++multidimensional-arraydelete-operator

Deleting 2d array in C++


Can some one tell me what is wrong in the for loop? When I run it, it interrupts. I tried to debug to see what is wrong, I noticed that in the for loop it just stops:

#define MAX_POPULATION 64
float **tr_pop;//Tournament candidates
float **matingPool;//Mating pool
tr_pop=new float *[m];
matingPool=new float *[m];
for(l=0;l<m+1;l++)//allocating
{
    tr_pop[l]=new float[MAX_POPULATION];
    matingPool[l]=new float[MAX_POPULATION];
}
for ( int r = 0; r < row; ++r )//deleting
{
 delete [] matingPool[r];//Stops here (not ending program just frozen)
 delete [] tr_pop[r];
}
delete [] tr_pop;
delete [] matingPool;

=======OK. PROBLEM SOLVED=======

Here is the reason:

I just changed the MAX_POPULATION into the MAX_POPULATION+1 and it worked.

for(l=0;l<m+1;l++)
    {
    tr_pop[l]=new float[MAX_POPULATION+1];
    matingPool[l]=new float[MAX_POPULATION+1];
    }

Because in another function I think I was doing violation:

void crossover()
{
int p1,p2,i,j;float tempBit;
p1=m/3;
p2=(2*m)/3;
for(j=0;j<MAX_POPULATION;j++)
{
    for(i=p1;i<p2;i++)
    {
    tempBit=matingPool[i][j];
    matingPool[i][j]=matingPool[i][j+1];//THE VIOLATION POINT (I THINK)
    matingPool[i][j+1]=tempBit;
    }
    j++;
}

As you can see, when j = MAX_POPULATION at the end of the loop, i was trying to reach MAX_POPULATION + 1. So I changed the allocations for columns, and the problem solved :)


Solution

  • You're running into undefined behavior:

    for(l=0;l<m+1;l++)//allocating
    {
        tr_pop[l]=new float[MAX_POPULATION];
    }
    

    should be

    for(l=0;l<m;l++)//allocating
    {
        tr_pop[l]=new float[MAX_POPULATION];
    }
    

    You're allocating m elements for each of the arrays and try to access m+1.