Aidan Mcgoff Aidan Mcgoff - 1 year ago 68
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);

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download