【发布时间】:2015-03-04 21:49:32
【问题描述】:
我正在做关于矩阵乘法的作业。我想找到我可以处理(分配)的最大矩阵的问题。于是我写了如下代码:
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 !
【问题讨论】:
-
这可能是因为在第二个示例中,您为 A 和 B 分配二维数组,但为 C 分配一维数组。(另外,don't cast the result of calls to
malloc().) -
真的很高兴在每个与 malloc 相关的帖子中看到 stackoverflow.com/questions/605845/…。
-
您刚刚编辑了您的帖子以使
C的分配更大......这将改变运行程序的行为 -
另外,你怎么知道“它不会停止递增 n”?
-
@MattMcNabb 我并不是说它不会停止递增 n,而是我的意思是 n 与第一个代码的结果相比太大了