besoin d'eclaircissement sur malloc et free
Bonjour à tous
Je pédale un peu dans la semoule avec ces 2 fonctions là ...
Après quelques recherches pour avoir des exemples je suis tombé la dessus :
Code:
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 42 43 44 45 46 47 48 49 50 51 52
| /* illustration of dynamically allocated 2D array */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i; /* general purpose variable used for loop index */
int j; /* general purpose variable used for loop index */
int **a; /* this is the array name */
int size_x; /* this variable will be used for the first dimension */
int size_y; /* this variable will be used for the second dimension */
/* suppose we want an array of int: a[5][3] */
size_x = 5;
size_y = 3;
/* allocate storage for an array of pointers */
a = malloc(size_x * sizeof(int *));
/* for each pointer, allocate storage for an array of ints */
for (i = 0; i < size_x; i++) {
a[i] = malloc(size_y * sizeof(int));
}
/* just for kicks, show the addresses (note: not all sequential) */
/* assign an arbitrary value to each element */
for (i = 0; i < size_x; i++) {
for (j = 0; j < size_y; j++) {
printf("&a[%d][%d] = %p\n", i, j, &a[i][j]); /* show the addresses */
a[i][j] = i * size_y + j; /* just some unique number for each element */
}
printf ("\n");
}
/* now show the contents that were assigned */
for (i = 0; i < size_x; i++) {
for (j = 0; j < size_y; j++) {
printf("a[%d][%d] = %2d\n", i, j, a[i][j]);
}
printf ("\n");
}
/* now for each pointer, free its array of ints */
for (i = 0; i < size_y; i++) {
free(a[i]);
}
/* now free the array of pointers */
free(a);
return 0;
} |
Si j'ai bien compris, on crée d'abord une variable **a, en gros un pointeur sur les colonnes qui pointe sur les lignes. Puis on attribut le nombre de colonnes en faisant :
Code:
a = malloc(size_x * sizeof(int *));
Et on défini le nombre de lignes en faisant :
Code:
1 2 3
| for (i = 0; i < size_x; i++) {
a[i] = malloc(size_y * sizeof(int));
} |
On a donc un tableau contenant size_x colonnes, qui contiennent size_y lignes.
Jusque là je crois que c'est bon, c'est après que ça se complique :
Code:
1 2 3
| for (i = 0; i < size_y; i++) {
free(a[i]);
} |
Si je comprends bien on va libérer les lignes crée avec
Code:
1 2 3
| for (i = 0; i < size_x; i++) {
a[i] = malloc(size_y * sizeof(int));
} |
Mais alors pourquoi il utilise size_y pour libérer les a[i] alors que le malloc était avec size_x ?
Je suis donc un peu embrouiller avec la libération, car selon moi il aurait fallu faire :
Code:
1 2 3
| for (i = 0; i < size_x; i++) {
free(a[i]);
} |