Aidan Mcgoff Aidan Mcgoff - 20 days ago 7
C Question

Trouble with freeing malloc'd 2d array in C

I have had trouble freeing my array. I have tried different methods, tried freeing by just one for loop, but I am honestly really stuck. Here is my code, any help is appreciated!

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){

int r,c,i,j, *array;
int sum = 0;
array = (int *)malloc(r*c*sizeof(int));

printf("Enter the number of rows: ");
scanf("%d", &r);
printf("Enter the number of columns: ");
scanf("%d", &c);

for(i=0;i<r;i++){
for(j=0;j<c;j++){
array[i*c+j] =+ i+j;
sum = sum + array[i*c+j];
}
}
printf("The sum of the array is: %d",sum);
for(i=0;i<r;i++){
for(j=0;j<c;j++){
free(array[i*c+j])
}
}
free(array);
return 0;
}

Answer

First off, you're allocating the array before you even know what the dimensions are...this will lead to undefined behavior, as r and c have undefined values.

To fix it, move the malloc call after the two scanfs.

Second, you only call malloc once - thus, you only need to/should call free once. Get rid of the two for loops with the free in the middle.