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

  • 本文关键字:分配 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=%dn",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=%dn",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

知道吗??

编辑
我是否投射malloc的结果?附言:我的教授告诉我们要经常使用malloc中的cast!!

您的程序在分配C之前很久就分配不到A或B了,C要小得多。在n约为21263的情况下,n*n是n的21263倍。循环将持续约10000次重复。如果在成功分配后释放C,循环甚至会持续数亿次重复,直到n达到约21263*21263。您只需要等待足够长的时间,程序就可以退出。

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

您可以尝试进行单个分配,然后将B和C的指针分配为a的偏移量。与其从一个小值开始,不如从一个在第一个循环中失败的大值开始,这样当分配成功时,堆就不会被分割。

相关内容

  • 没有找到相关文章

最新更新