修改二维数组的malloc策略,使malloc成功 [英] Modify malloc strategy for 2D Array so malloc succeeds

查看:180
本文介绍了修改二维数组的malloc策略,使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))

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

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?

请记住,我有大量的代码访问此对象,如下所示:array [row] .col [colNum],所以我需要一些需要次要或主要找到&

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.

推荐答案

您可以单独分配更小的内存块,

You can allocate smaller chunks of memory separately, instead of one huge block.

long** array = NULL;  
array = (long**) malloc(numCols * sizeof(long*));  
for (int i = 0; i < numCols; i++)  
   array[i] = (long*)  malloc(numRows * sizeof(long));

一般来说,内存分配可能失败,每次分配。然而,让我们说在统计上,由于内存碎片,分配单个大块内存更高的机会比分配N个更小的块更频繁地失败。
虽然,上述解决方案也可能会导致问题,因为它有点像双刀剑,因为它可能导致进一步的内存碎片。

Generally, memory allocation may fail, every allocation. However, let's say statistically, due to memory fragmentation, allocating a single large block of memory has higher chance to fail more often than allocating N number of smaller blocks. Although, also the solution above may cause problems as it is a bit like a double-bladed sword because it may lead to further memory fragmentation.

在其他字,没有一般完美的答案,解决方案取决于系统和应用程序的细节。

In other words, there is no generally perfect answer and solution depends on details of a system and application.

从评论来看,似乎C ++库是一种可能性,然后解决方案基于 std :: vector (例如 C ++中的向量通用矢量)或使用 Boost.MultiArray

As from the comments it seems C++ library is a possibility, then solution based on std::vector (i.e. generic vector of vectors in C++) or using Boost.MultiArray

这篇关于修改二维数组的malloc策略,使malloc成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆