Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify malloc strategy for 2D Array so malloc succeeds

Tags:

c++

c

malloc

We recently received a report that our application will occasionally fail to run. I tracked down the problem code to this:

struct ARRAY2D
{
   long[] col;
}

int numRows = 800000;
int numCols = 300;
array = (ARRAY2D*) malloc(numRows * numCols * sizeof(long))

This allocation of 800 Mb can fail if the user doesn't have a large enough free block. What is the best way to change how I allocate the memory?

Keep in mind that I have a large amount of code that accesses this object like this: array[row].col[colNum], so I need something that requires minor or primarily find & replace editing of the array access code.

like image 252
Brian Avatar asked Apr 02 '26 03:04

Brian


1 Answers

Will there be a lot of default values in your ARRAY2D? If yes, you need a sparse array. The minimal change would be to use an unordered_map (or hash_map or map):

static const int numRows = 800000;
static const int numCols = 300;

struct ARRAY2D {
  long col[numCols];
  // initialize a column to zero; not necessary.
  ARRAY2D() { memset(col, 0, sizeof(col)); }
};


// no need to malloc
std::unordered_map<int, ARRAY2D> array;
...
// accessing is same as before ...
array[1204].col[212] = 4423;
printf("%d", array[1204].col[115]);
...
// no need to free.

If the row indices are always continuous but much less than numRows, use a std::vector instead.

std::vector<ARRAY2D> array;
...
// resize to the approach value.
array.resize(2000);
...
// accessing is same as before ...
array[1204].col[212] = 4423;
printf("%d", array[1204].col[115]);
...
// no need to free.
like image 96
kennytm Avatar answered Apr 03 '26 17:04

kennytm