cmatrixfreealloc

free 2d array(matrix) of struct named "cell" where each of them as member of string(char*)


Allocations :

cell **initBoard(int boardSize)
{
    int i, j, k;
    cell **matrix;
    matrix = (cell **) malloc((boardSize + 1) * sizeof(cell *));

    // init upper frame
    matrix[0] = (cell *) malloc((boardSize + 1) * sizeof(cell));
    matrix[0][0].type = (char *) malloc(3 * sizeof(char));
    matrix[0][0].type[0] = ' ';

    for (k = 1; k <= boardSize; k++)
    {
        // +1 for null char ?
        matrix[0][k].type = (char *) malloc(3 * sizeof(char));
        matrix[0][k].type = arrNo[k - 1];
    }

    // init inner rows
    for (i = 1; i <= boardSize; i++)
    {
        matrix[i] = (cell *) malloc((boardSize + 1) * sizeof(cell));

        // first letter each row
        matrix[i][0].type = (char *) malloc(3 * sizeof(char));
        matrix[i][0].type[0] = (char) (BASE_ALPHABET + i);

        // init cols
        for (j = 1; j <= boardSize; j++)
        {
            matrix[i][j].type = (char *) malloc(2 * sizeof(char) + 1);
            matrix[i][j].type[0] = EMPTY;
            matrix[i][j].type[1] = WATER; // default status
            matrix[i][j].hidesShip = NULL;
        }
    }
    return matrix;
}

Deallocations :

void freeMatrix(cell **matrix, int boardSize)
{
    int k, l;
    for (k = 0; k <= boardSize; k++)
    {
        for (l = 0; l <= boardSize; l++)
        {
            free(matrix[k][l].type);
        }
        free(matrix[k]);
    }
    free(matrix);
}

I run the code above(malloc + free are showed) and then checked memory-leak with Valgrind and got this output :

Valdrind Log Any idea what I am doing wrong here? The Valgrind means I did one extra free command? I cant see where exactly because I moved over all cells.. maybe better understanding of pointers is required here? thanks.


Solution

  • matrix[0][k].type = (char *) malloc(3 * sizeof(char));
    matrix[0][k].type = arrNo[k - 1];
    

    The problem is that you are allocating memory and immidiatly after you write to the pointer holding the address. You can no longer access the memory therefore valgrind reports it as leaked.

    You probably wanted to write

        matrix[0][k].type[0] = arrNo[k - 1];
    

    Assuming that arrNo is a character array, the first assignment would be illegal since you are assigning char to char *. Your compiler should have given you a warning.