开发者

Memory issues with two dimensional array

Following this nice example I found, I was trying to create a function that dynamically generates a 2D grid (two dimensional array) of int values.

It works fairly well the first couple of times you change the values but if crashes after that. I guess the part where memory is freed doesn't work as it should.

void testApp::generate2DGrid() {
    int i, j = 0;

    // Delete previous 2D array
    // (happens when previous value for cols and rows is 0)
    if((numRowsPrev != 0) && (numColumnsPrev != 0)) {
        for (i = 0; i < numRowsPrev; i++) {
            delete [ ] Arr2D[i];
        }
    }

    // Create a 2D array
    Arr2D = new int * [numColumns];
    for (i = 0; i < numColumns; i++) {
        Arr2D[i] = new int[numRows];
    }

    // Assign a random values
    for (i=0; i<numRows; i++) {
        for (j = 0; j < numColumns; j++) {
            Arr2D[i][j] = ofRandom(0, 10);
        }
    }

    // Update previous value with new one
    numRowsPrev = 开发者_运维百科numRows;
    numColumnsPrev = numColumns;
}


I see 1 major bug:

// Assign a random values
for (i=0; i<numRows; i++){
    for (j=0; j<numColumns; j++){
        Arr2D[i][j] = ofRandom(0, 10);
    }
}

Here the variable 'i' is used as the first index into 'Arr2D' and goes to a max of (numRows -1)
While in this code:

for (i=0; i<numColumns; i++)
{
    Arr2D[i] = new int[numRows];
}

The variable 'i' is used as the first index but goes to a max of (numColumns-1). If numRows is much larger than numColumns then we are going to have a problem.

As a side note. When you try and clean up you are leaking the columns:

if((numRowsPrev != 0) && (numColumnsPrev != 0))
{
    for (i=0; i<numRowsPrev; i++){
        delete [ ] Arr2D[i];
    }
    // Need to add this line:
    delete [] Arr2D;
}

Next thing to note.
This is truly not a good idea. Use some of the provided STL classes (or potentially boost Matrix). This looks like you are binding global variables and all sorts of other nasty stuff.


2-dim array in C++ with no memory issues:

#include <vector>

typedef std::vector<int> Array;
typedef std::vector<Array> TwoDArray;

Usage:

TwoDArray Arr2D; 

// Add rows
for (int i = 0; i < numRows; ++i) {
    Arr2D.push_back(Array());
}

// Fill in test data
for (int i = 0; i < numRows; i++) {    
    for (int j = 0; j < numCols; j++) {
        Arr2D[i].push_back(ofRandom(0, 10));           
    }
}

// Make sure the data is there
for (int i = 0; i < numRows; i++) {    
    for (int j = 0; j < numCols; j++) {
        std::cout << Arr2D[i][j] << ' ';
    }
std::cout << '\n';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜