gpt4 book ai didi

c++ - 修改 2D Array 的 malloc 策略,使 malloc 成功

转载 作者:太空狗 更新时间:2023-10-29 23:38:10 24 4
gpt4 key购买 nike

我们最近收到报告说我们的应用程序偶尔会运行失败。我追踪到问题代码是这样的:

struct ARRAY2D
{
long[] col;
}

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

如果用户没有足够大的空闲 block ,800 Mb 的分配可能会失败。更改内存分配方式的最佳方法是什么?

请记住,我有大量代码像这样访问此对象:array[row].col[colNum],因此我需要一些需要次要或主要查找和替换的东西编辑数组访问代码。

最佳答案

ARRAY2D 中会不会有很多默认值?如果是,则需要一个稀疏数组。 最小的变化是使用unordered_map(或hash_mapmap):

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.

如果行索引始终连续但远小于 numRows,请改用 std::vector

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.

关于c++ - 修改 2D Array 的 malloc 策略,使 malloc 成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2213342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com