Memory issues with two dimensional array

大城市里の小女人 提交于 2019-12-07 05:38:25

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';
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!