Error when attempting to use the heap

86 views Asked by At

I've written a program that works for most input, but if I ask it to make a increase precision by using a larger array (about 320x320 was when I started seeing trouble) it crashes. I searched for my issue online and found this similar problem and this tutorial on what to do about it. The problematic part of my original code is below - I had precision=320 and holepop=770.

double spacing = 2.0/(precision+1);
int lattice_int[precision][precision];
for (i=0; i<precision; ++i){
    for (ii=0; ii<precision; ++ii){
        mindist_sq = 2.0;
        lattice_int[i][ii] = 0;
        for (iii=0; iii<holepop; ++iii){
            xdist = abs(xcoord[iii] + 1.0 - spacing/2 - spacing*i);
            ydist = abs(ycoord[iii] - 1.0 + spacing/2 + spacing*ii);
            thisdist_sq = xdist*xdist+ydist*ydist;
            if (thisdist_sq < mindist_sq){
                 lattice_int[i][ii] = dint[iii];
                 mindist_sq = thisdist_sq;
            }
        }
    }
}

I tried to fix it with this change in the first two lines:

int * lattice_int;
double spacing = 2.0/(precision+1);
lattice_int = new int[precision][precision];

(I also put in "delete lattice_int[][];" at the end.) However, I received this error: 'precision' cannot occur in a constant expression Is it because I'm trying to work with multiple indices? What can I do to work around my problem? Thank you!

2

There are 2 answers

2
Puppy On BEST ANSWER

Don't use new[], it'll only cause you pain, suffering, memory leaks, use-after-frees, etc.

You can use std::vector in this respect.

std::vector<std::vector<int>> lattice_int(precision, std::vector<int>(precision));

No memory freeing necessary.

3
Mital Vora On

Your lattice_int variable is 2d array. You can allocate it using following code:

int precision = 500;
int ** lattice_int;
double spacing = 2.0/(precision+1);

lattice_int = new int*[precision];
for (int i = 0; i < precision; i++)
{
    lattice_int[i] = new int[precision];
}

Same way you have to iterate for deletion of each sub array.

Note: This is pure illustration to use pointers for creating two dimensional array. The better way would be to use vector for this.