hoholee12
hoholee12

Reputation: 334

creating a 2d array using double pointer

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?

Upvotes: 0

Views: 60

Answers (1)

PC Luddite
PC Luddite

Reputation: 6088

This

arr=(int **)calloc(row, sizeof(int));

should be

arr = calloc(row, sizeof(int*));

(note that the cast is not required in C and actually discouraged)

So on implementations where the size of a pointer is not the size of int (e.g. on x64 machines), you will invoke undefined behavior when you read outside the bounds of allocated memory.

You might consider not using an explicit type as the operand of sizeof.

arr = calloc(row, sizeof*arr);

This lets the compiler deduce the type and will help you avoid errors like this.

Upvotes: 2

Related Questions