修改的malloc战略二维数组,这样成功的malloc [英] Modify malloc strategy for 2D Array so malloc succeeds
问题描述
我们最近收到一份报告,我们的应用程序有时可能不运行。我找到了问题所在code这样:
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兆的这种分配,如果用户不具有一个足够大的空闲块可能会失败。什么是改变我如何分配内存的最好方法?
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?
请记住,我有一个访问该对象像这样大量的code的:数组[行] .COL [colNum],所以我需要的东西,需要的未成年人或主要查找和放大器;更换阵列访问code的的编辑。
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 ::矢量
(即<一href=\"http://stackoverflow.com/questions/293988/generic-vector-of-vectors-in-c/2211411#2211411\">generic在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屋!