sherrellbc
sherrellbc

Reputation: 4853

Allocate and free 2D array in C using void

The idea is to use only two functions that can both allocate and free a 2D array of a given data type that is not known at compile-time. The code I have written crashes in the freeing function, but I cannot see why. Here is the code:

void** new2DArray(int row, int col, int typeSize){
    void** temp = malloc(sizeof(void*)*row); //EDIT                     
    for (row-=1; row >= 0; row--)                               
        temp[row] = malloc(typeSize*col);
    return temp; 
}


void free2DArray(void** array, int row, int typeSize){
    for (row -= 1; row >= 0; row--)
        free( *(array + row*typeSize) );
     free(array); 
}

Where, for a 3x3 array, is would be called like:

double** test = (double**) new2DArray(3, 3, sizeof(double));
free2DArray(test, 3, sizeof(double));

Is there anything immediately wrong with the freeing function?

Upvotes: 0

Views: 3445

Answers (3)

s.bandara
s.bandara

Reputation: 5664

You free column arrays with free(*(array + row*typeSize));. However, it should be free(*(array + row)), or more concisely, free(array[row]). array + row*typeSize makes you skip typeSize number of column vectors per iteration, and hence, "free" columns that were never allocated.

Upvotes: 1

brokenfoot
brokenfoot

Reputation: 11629

Why not free it the same way you are allocating it?

for (row-=1; row >= 0; row--)                               
        free(array[row]); 
      //free(*(array + row)); <- or the way you are doing it
free(array);

Upvotes: 1

pat
pat

Reputation: 12749

The free2DArray looks wrong. You don't need to know the size of the types; you just free the blocks that you allocated:

void free2DArray(void** array, int row){
    for (row -= 1; row >= 0; row--)
        free( array[row] );
     free(array); 
}

Upvotes: 3

Related Questions