C正确地释放多维数组

时间:2014-09-11 18:54:42

标签: c arrays multidimensional-array valgrind free

我有以下代码,我真的不明白为什么我有分段错误

static char** game_alloc(char **game, int n, int m) {
    game = calloc(n, sizeof(char *));
    for(int i = 0; i < n; i++)
    {
        game[i]= calloc(m, sizeof(char));
    }
    if(*game == NULL) {
        perror("Error: calloc in not initialized correctly");
        exit(EXIT_FAILURE);
    }
    return game;
}

static void game_free(char **game, int n) {

    for (int i = 0; i < n; i++) { 
        free(game[0]);
    }
    free(game);
}

问题是当我调用函数game_free时。我对free

有一个分段错误

当我将其运行到valgrind时,我有这个:

==11449== Use of uninitialised value of size 8
==11449==    at 0x400AE5: game_free (john.c:27)
==11449==    by 0x400DAE: main (john.c:114)
==11449== 
==11449== Invalid free() / delete / delete[] / realloc()
==11449==    at 0x4C29730: free (vg_replace_malloc.c:468)
==11449==    by 0x400AEF: game_free (john.c:27)
==11449==    by 0x400DAE: main (john.c:114)
==11449==  Address 0x495641ff89415741 is not stack'd, malloc'd or (recently) free'd
==11449== 
==11449== Conditional jump or move depends on uninitialised value(s)
==11449==    at 0x4C296E6: free (vg_replace_malloc.c:468)
==11449==    by 0x400B07: game_free (john.c:29)
==11449==    by 0x400DAE: main (john.c:114)
==11449== 
==11449== Invalid free() / delete / delete[] / realloc()
==11449==    at 0x4C29730: free (vg_replace_malloc.c:468)
==11449==    by 0x400B07: game_free (john.c:29)
==11449==    by 0x400DAE: main (john.c:114)
==11449==  Address 0x400f10 is in the Text segment of /autofs/netapp/account/cremi/mpuygren/MasterCSI/projet/john-2/john
==11449== 
==11449== 
==11449== HEAP SUMMARY:
==11449==     in use at exit: 33 bytes in 4 blocks
==11449==   total heap usage: 4 allocs, 4 frees, 33 bytes allocated

不明白,我跟着这篇文章,但......

C: Correctly freeing memory of a multi-dimensional array

2 个答案:

答案 0 :(得分:3)

应该是free(game[i]);,而不是free(game[0]);

答案 1 :(得分:1)

而不是:

for (int i = 0; i < n; i++) { 
        free(board[0]);
    }

写:

for (int i = 0; i < n; i++) { 
        free(board[i]);
    }