Search code examples
cmemory-managementmemory-leaksdynamic-arrays

Memory leaking when allocating memory


I have a function which creates a 2D array:

float** createMatrix(int x, int y){
    float** array= malloc(sizeof(float*) * y);
    for(int i=0; i<y; i++)
        array[i] = malloc(sizeof(float) * x);
    return array;
}

Now I can create a 2D array:

    float** temp=createMatrix(2,2);

I also have a function, for e.g., which transposes my "matrix" (2D array):

float** matrixTranspose(float** m, int x, int y){
    float** result=createMatrix(y, x);
    for(int i=0; i<y; i++){
        for(int j=0;j<x; j++) result[j][i]=m[i][j];
    }
    return result;
}

Now if I do this:

temp=matrixTranspose(temp,2,2);

what happens with the old memory previously allocated to temp? My transpose function allocates new memory chunk. Obviously I would have to somehow free "old temp" after the Transposition, but how (elegantly)?


Solution

  • Your free can mirror your allocation:

    int i;
    for(i = 0; i < y; i++)
        free(array[i]);
    free(array);
    

    But if you assign to temp the new matrix created by matrixTranspose, then you'll lose your pointer to that memory. So keep track of that with another pointer, or assign the result of matrixTranspose to another pointer:

    float **transposedMatrix = matricTranspose(...);
    

    If you consider your matrices as mutable, you could also transpose them in place: rather than allocating a new matrix in the matrixTranspose function, you move around the numbers in the existing array. You can do this in place with one float temp.