Bonjour à toutes et à tous,
La fatigue n'aidant pas, je bloque sur une mise en place d'une allocation et d'une libération dynamique d'un tableau 3D.
Le problème surgit lorsque je fais la libération de la mémoire. J'ai pourtant bien essayé de respecter la règle un free pour un malloc :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 int*** allocate3Darray(int stack, int width, int height){ int ***ptr; int i, j; ptr = malloc (stack * sizeof (**ptr)); if( ptr == NULL){ return NULL; } //for (i = 0; i < width; i++){ for (i = 0; i < stack; i++){ ptr[i] = malloc( width * sizeof(*ptr)); if(ptr[i] == NULL){ for(--i ; i >=0; --i) free(ptr[i]); free(ptr); return NULL; } //for (j = 0; j < height; j++){ for (j = 0; j < width ; j++){ ptr[i][j] = malloc (height * sizeof (ptr)); if (ptr[i][j] == NULL){ for(--j; j >= 0 ; --j) free(ptr[i][j]); for(--i ; i >=0; --i) free(ptr[i]); free(ptr); return NULL; } } } return ptr; }En utilisation :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 //void free3Darray(int ***ptr, int width, int height){ void free3Darray(int ***ptr, int stack, int width){ int i, j; //for (i = 0; i < width; i++){ for (i = 0; i < stack; i++){ //for (j = 0; j < height; j++) for (j = 0; j < width; j++) free(ptr[i][j]); free(ptr[i]); } free(ptr); }
A la première exécution, pas de problème. Pour les suivantes, ça plante littéralement lors de la libération (dernier free()). Pas de message très exploitable du debugger.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 #include <stdio.h> #include <stdlib.h> int main() { int ***arr3d; int **arr2d; int x, y, z, count = 0; arr3d = allocate3Darray(2, 3, 3); if(arr3d == NULL) return EXIT_FAILURE; for( x = 0; x < 2 ; x++){ for( y = 0; y < 3; y ++){ for( z = 0; z < 3; z ++){ arr3d[x][y][z] = count; count ++; } } } arr2d = &arr3d[1][0]; for( x = 0; x < 3 ; x++){ for( y = 0; y < 3; y ++){ printf("%d ", arr2d[x][y]); } printf("\r\n"); } printf("\r\n"); arr2d = NULL; //free3Darray(arr3d, 3, 3); free3Darray(arr3d, 2, 3) return 0;
J'ai vu qu'un autre sujet proposait une solution mais j'aimerai comprendre où je faute.
EDIT : Le problème venait simplement de mon parcours de boucle lors de l'allocation ET de la libération qui ne suivait aucune logique ...
Partager