Search code examples
cmemorymallocruntimefree

Allocating memory for 2d matrix using 1 malloc call


We can allocate memory for 2d matrix using 1 malloc call as
int (*a)[5];
int i,j;

a=malloc(sizeof(int*) * 5); //allocating 5 pointers and each pointer points to an array of 5 ints

How can we free this memory allocated successfully? Using free(a) gives run-time error

Using for(i=0;i<5;i++) free(a[i]);

free(a);

This also gives run-time error


Solution

  • Edit: THE WHOLE STORY.

    Previously I ignored THREE other ways to allocate 2d arrays.

    Dynamic 2d array method 1:

    This one works if you know the the number of columns at compile time.

    #define CCOLS 200
    
    int (*m)[CCOLS] = malloc(cRows * sizeof(*m));
    m[iRow][iCol] = n; // sets the item at iRow*CCOLS + iCol
    
    ...
    
    free(m);
    

    This works because m is declared as a pointer to an array of CCOLS ints. The compiler knows its size and does the math for you. m[iRow] = an array of CCOLS ints.

    You can only pass this to functions with this signature:

    foo(int (*m)[CCOLS]) { ... }
    

    and maybe this signature, depending upon your compiler and the switches you use:

    foo(int m[][CCOLS]) { ... }
    

    not this signature:

    foo(int **m) { ... }
    

    Since the memory layouts and sizes are different.

    int m[][CCOLS] looks like this:

    +---------+---------+---------+---------+     
    | m[0][0] | m[0][1] | m[0][2] | m[0][3] |     
    +---------+---------+---------+---------+     
    | m[1][0] | m[1][1] | m[1][2] | m[1][3] |     
    +---------+---------+---------+---------+     
    | m[2][0] | m[2][1] | m[2][2] | m[2][3] |     
    +---------+---------+---------+---------+     
    | m[3][0] | m[3][1] | m[3][2] | m[3][3] |     
    +---------+---------+---------+---------+     
    

    int **m looks like this:

    +----+        +----+----+----+----+----+      
    |m[0]|  --->  |    |    |    |    |    |      
    +----+        +----+----+----+----+----+      
    |m[1]|  --->  |    |    |    |    |    |      
    +----+        +----+----+----+----+----+      
    |m[2]|  --->  |    |    |    |    |    |      
    +----+        +----+----+----+----+----+      
    |m[3]|  --->  |    |    |    |    |    |      
    +----+        +----+----+----+----+----+      
    

    Dynamic 2d array method 2 (C99 which is not supported by all compilers):

    This one is the same as the previous but you don't need to know dimensions at compile time.

    int cCols, cRows, iCol, iRow;
    ... set cRows, cCols somehow, they could be passed in as parameters also ...
    int (*m)[cCols] = malloc(cRows * sizeof(*m));
    m[iRow][iCol] = n; // sets the item at iRow*cCols + iCol
    
    ...
    
    free(m);
    

    You can only pass this to functions with this signature:

    foo(int cCols, m[][cCols])  {}
    

    or this one

    foo(int cRows, int cCols, m[cRows][cCols])  {}
    

    If you use gcc, here is more info.

    Dynamic 2d array method 3 using the STACK! (C99 which is not supported by all compilers):

    This lets you avoid malloc entirely if you are ok with your 2d array on the stack.

    int cRows, cCols;
    ... set cRows, cCols somehow ...
    int m[cRows][cCols];
    m[iRow][iCol] = n; 
    

    I assume you could declare a global variable this way too.

    You pass this to functions the same way as method 2.

    Dynamic 2d array method 4:

    This is the array of pointers method that a lot of people use.

    You use one malloc to allocate to be efficient. And of course you then only use one free. Only if you have HUGE arrays where contiguous memory becomes and issue, would you want to malloc each row individually.

    int cCols = 10, cRows = 100, iRow;
    
    // allocate:
    // cCols*cRows*sizeof(int) = space for the data
    // cRows*sizeof(int*) = space for the row ptrs
    int **m = malloc(cCols*cRows*sizeof(int) + cRows*sizeof(int*));
    
    // Now wire up the row pointers.  They take the first cRows*sizeof(int*) 
    // part of the mem becasue that is what m[row] expects.
    // we want each row pointer to have its own cCols sized array of ints.
    // We will use the space after the row pointers for this.
    // One way to calc where the space after the row pointers lies is to
    // take the address of the nth + 1 element: &m[cRows].
    // To get a row ptr, cast &m[cRows] as an int*, and add iRow*cCols to that.
    for (iRow = 0; iRow < cRows; ++iRow)
        m[iRow] = (int*)&m[cRows] + iRow*cCols; 
    
    // or 
    for (p=(int*)&m[cRows] ; iRow = 0; iRow < cRows; ++iRow, p+=cCols)
        m[iRow] = p; 
    
    
    // use it:
    ...
    m[iRow][iCol] = 10;
    ...
    
    // free it
    free(m);