0

I have this following code, and i really don't understand why i have this segmentation fault

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);
}

The problem is when i call the function game_free. I have a segementation fault with the free

When i run it into valgrind i have this :

==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

Don't understand, i follow this post but ....

C: Correctly freeing memory of a multi-dimensional array

Community
  • 1
  • 1
mpgn
  • 7,121
  • 9
  • 67
  • 100
  • Just to spread the word, this is **not** a multidimensional array. It is only an emulation of it. C has real multidimensional arrays with variable bounds since 1999. Among other things you would avoid this particular problem by using the correct tool from the start. – Jens Gustedt Sep 11 '14 at 20:36

2 Answers2

3

It should be free(game[i]);, instead of free(game[0]);

ani627
  • 5,578
  • 8
  • 39
  • 45
1

Instead of:

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

write:

for (int i = 0; i < n; i++) { 
        free(board[i]);
    }
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32