Search code examples
cmallocfree

Issue Freeing 2D Dynamic Memory


I'm unsure what the problem running this is. I know that if I remove the second for loop (where it is supposed to free the inner array), it runs fine.

int main(void)
{
    int i;
    char *board = malloc(sizeof(char *) * 8);
    for (i=0; i<8; i++)
        board[i] = malloc(sizeof(char *) * 8);

    for (i=0; i<8; i++)
        free(board[i]);
    free(board);
    return 0;
}

Solution

  • The variable board is a pointer to char, i.e. much like a string. That means each "element" in board is a single character and not a pointer.

    That means when you in the loop do

    board[i] = malloc(sizeof(char *) * 8);
    

    you will assign a pointer to a char, and not a char *.

    You want to make board a pointer to pointers to char:

    char **board = malloc(...)
    

    Oh and by the way, you are allocating more than 8 characters for each string in the loop. You are allocating memory for 8 pointers. You should do e.g.

    board[i] = malloc(sizeof(char) * 8);
    

    Or, since sizeof(char) is always equal to 1

    board[i] = malloc(8);
    

    Furthermore, and I don't know if this applies to you, but remember that strings in C have a special terminator character at the end. So if you want a string of eight characters you need to make space for nine characters.