在c中分配给矩阵的最大大小

时间:2015-03-04 21:49:32

标签: c matrix malloc

我正在做矩阵乘法的作业。我想找到我能处理的最大矩阵(分配)的问题。所以我写了下面的代码:

int n = 1;
while(1){
n++;
A=malloc(sizeof(double)*n*n);                                                                                                                           
B=malloc(sizeof(double)*n*n);
C=malloc(sizeof(double)*n*n);
if (C==NULL) {printf("Error No more size to allocate! n=%d\n",n); return 1;} 
// and the rest of the code including freeing the allocate

结果:

Error No more size to allocate! n=21785

现在我想使用另一种方法:使用A作为结果而不是C. 所以我只需要2(n ** 2)+ n而不是3(n ** 2)。
所以新代码应该像这样:

int n = 1;
while(1){
n++;
A=malloc(sizeof(double)*n*n);                                                                                                                           
B=malloc(sizeof(double)*n*n);
C=malloc(sizeof(double)*n);
if (C==NULL) {printf("Error No more size to allocate! n=%d\n",n); return 1;} 
// and the rest of the code including freeing the allocated space.

当我运行此代码时它不会停止递增n但是如果我将条件从(C==NULL)更改为(A==NULL||B==NULL||C==NULL)的问题 结果是:

Error No more size to allocate! n=21263

任何想法??

修改
Do I cast the result of malloc? PS:我的教授告诉我们总是在malloc中使用cast!

3 个答案:

答案 0 :(得分:1)

您的程序在分配无法分配A之前很久就分配了A或B,这个C要小得多。当n约为21263时,n * n比n大21263倍。循环将持续大约10000次重复。如果在成功分配后释放C,循环甚至会持续几亿次重复,直到n达到约21263 * 21263。你只需要等待足够长的时间让你的程序退出。

答案 1 :(得分:0)

there are a few things to note

1) the main consideration is that memory, once allocated (by malloc and not free'd) means the amount of available heap to allocate goes down, even as 'n' goes up.

2) any call to malloc() can fail, including the first call
   this means the failure could be any of the calls to malloc()

3) in C, the returned value from malloc (and family) should not be cast.

4) the returned value from malloc() should always be checked, 
   not just one in three calls to malloc()

regarding the posted code. 
1) all the above considerations should be implemented
2) in the second example of posted code, just because a 
   larger memory request (n*n) fails  does not mean a 
   smaller request (n) would fail.
   that is why the modification catches the failure of 'A'

3) the heap address and the size of the heap are normally 
   available at compile time, so there is no need
   for the kind of code you posted

答案 2 :(得分:0)

您可以尝试进行单个分配,然后将B和C的指针指定为A的偏移量。而不是从较小的值开始,从一个应该在第一个循环上失败的大值开始,这样当分配时成功后,堆不会碎片化。

相关问题