简体   繁体   中英

Corrupted heap error when declaring a double* array

I'm currently working on finding the sum of squared distances of two matricies, the data is held in double* arrays. the first of them stays the same while the other is cycled through using a function that returns a 32x32 array between two indices.

However when i try and call "getTile(d,e)" after the first incrementation of "e" it throws a heap corruption exception:

double* Matrix::ssd(int i, int j, Matrix& rhs){
double sum = 0, val = 0; int g = 0, h=0;
double* bestMatch = new double[32*32]; double* sameTile = new double[32*32];    double* changeTile = new double[32*32]; 

for(int x = i-32; x <i; x++){
    for(int y = j-32; y <j; y++){
        sameTile[g*32+h] = data[x*N+y];
        h++;
    }g++; h = 0;
}

system("pause");

for(int d = 32; d<=512; d+=32){
    for(int e = 32; e<=512; e+=32){

        changeTile = rhs.getTile(d,e);

        for(int out = 0; out < 32; out++){
            for(int in = 0; in < 32; in++){
                val = sameTile[out*32+in] - changeTile[out*32+in];
                val = val*val;
                sum = sum + val;

            }       
        }
        cout << sum << endl;

        sum = 0; val = 0;

        system("pause");
    }   
}

The getTile(int i, int j) function:

double* Matrix::getTile(int i, int j){
double* tile = new double[32*32]; int g = 0; int h = 0;
for(int x=i-32; x<i; x++){
    for(int y=j-32; y<j; y++){
        tile[g*32+h] = data[x*N+y];
        h++;
    }
    cout << endl;
    g++;
}
return tile;
}

I believe the error occurs with the allocation of memory in the changeTile double*?

Any help would be very much appreciated.

There are a bunch of issues in your code all related to improperly accessing array elements.

In the first loop the line:

 sameTile[g*32+h] = data[x*N+y];

at the very least underflows the data array. Consider if i=0, j=0, and N=512 then you are trying to access data[-16416] in the first pass of the loop.

Second issue is the getTile() method where you forget to reset h to 0 at the end of the inner loop (like you do in the ssd() method). This results in the overflow of tile[]

I would also double-check the line:

 changeTile = rhs.getTile(d, e);

and the method getTile() to ensure an array overflow doesn't occur on data[].

Overall I would suggest using proper std:: containers if at all possible. Using them correctly should completely eliminate this type of error. If you really do need to use raw pointers/arrays then you need to make sure all your indexing into them is as clear as possible in addition to bounds checking where needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM