i have made a program that creates 2d array. the code below works well on visual studio & turbo c:
#include<stdio.h>
#include<stdlib.h>
int **allocarr(int **arr, int row, int col){
int i;
arr=calloc(row, sizeof(int));
for(i=0; i<row; i++){
arr[i]=calloc(col, sizeof(int));
}
return arr;
}
void freearr(int **arr, int row, int col){
int i;
for(i=0; i<row; i++) free(arr[i]);
free(arr);
}
void printarr(int **arr, int row, int col){
int i, j;
for(i=0; i<row; i++){
for(j=0;j<col;j++){
printf("\t%d", arr[i][j]);
}
printf("\n\n");
}
}
int main(){
int **arr=NULL;
arr=allocarr(arr, 3, 3);
arr[2][2]=8;
printarr(arr, 3, 3);
freearr(arr,3, 3);
return 0;
}
but it does not work on mac os x gcc and mingw gcc.
everything compiles fine without any warning and errors(-Wall & -Wextra),
but it crashes on runtime...
in gdb and lldb, it says that free()
is freeing a non-allocated memory.
after allocating a pointer array, when i allocate memory after that, exactly 2 of the memory block(is this the right word?) will have random values that cannot be initialized.
i tried allocating another array before i assign it to the pointer array. it prints fine(no 2 random values), but will still occasionally crash when assigning values on it. why is this happening?