I'am doing a homework on matrix multiplication. The problem that i want to find the largest matrix that i can handle (allocate). So i wrote the following code:
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
the result:
Error No more size to allocate! n=21785
Now i want to use another method: using A as the result instead of C.
So that i only need 2(n**2)+n instead of 3(n**2).
So the new code should loke like this :
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.
The problem that when i run this code it wont stop incrementing n but if i change the condition from (C==NULL)
to (A==NULL||B==NULL||C==NULL)
the result is:
Error No more size to allocate! n=21263
Any idea??
Edit
Do I cast the result of malloc?
PS: My professor tell us to always use cast in malloc!!