diff --git a/Programmation/Exercices/serie_08_prog1_corr.c b/Programmation/Exercices/serie_08_prog1_corr.c new file mode 100644 index 0000000000000000000000000000000000000000..749a2fff19e9e6a7c9914612f30a656a40a0782d --- /dev/null +++ b/Programmation/Exercices/serie_08_prog1_corr.c @@ -0,0 +1,34 @@ +#include <stdio.h> + +void foo(int a) { + a += 3; +} + +void bar(int *a) { + *a += 3; +} + +void baz(int *a) { + a += 3; +} + +int main() { + int a = 5; + printf("%i\n", a); + + // la fonction foo ne peut pas modifier son parametre + // c'est donc normal que a ne soit pas modifié + foo(a); + printf("%i\n", a); + + // la fonction bar prend un pointeur sur a + // ce qui lui permet de modifier a + bar(&a); + printf("%i\n", a); + + // la fonction baz pourrait modifier a + // mais son code modifie uniquement son pointeur + // en interne de la fonction + baz(&a); + printf("%i\n", a); +} \ No newline at end of file diff --git a/Programmation/Exercices/serie_08_prog2_corr.c b/Programmation/Exercices/serie_08_prog2_corr.c new file mode 100644 index 0000000000000000000000000000000000000000..b34940ee471150ec5e0d7a83b8f8d00507aee881 --- /dev/null +++ b/Programmation/Exercices/serie_08_prog2_corr.c @@ -0,0 +1,46 @@ +#include <stdio.h> +#include <stdlib.h> + +// le tableau statique tab[a] est désalloué à la fin de la fonction +// on le remplace par une allocation dynamique +int *foo(int a) { + int* tab = malloc(a*sizeof(int)); + for (int i = 0; i < a; ++i) { + tab[i] = 2; + } + return tab; +} + +// l'allocation était de a octets au lieu de a*sizeof(int) octets +int *bar(int a) { + int *tab = malloc(a*sizeof(int)); + for (int i = 0; i < a; ++i) { + tab[i] = 2; + } + return tab; +} + +// tab était réalloué à l'intérieu de baz sans que cela soit visible a l'exterieur +// cela a pour conséquence de ne pas initialiser l'espace mémoire vu a l'extérieur +// et de provoquer une fuite mémoire +void baz(int *tab, int b) { + for (int i = 0; i < b; ++i) { + tab[i] = 2; + } +} + +int main() { + int *a = foo(4); + printf("%d\n", a[3]); + + int *b = bar(4); + printf("%d\n", b[3]); + + int *c = malloc(4*sizeof(int)); + baz(c, 4); + printf("%d\n", c[3]); + + free(a); + free(b); + free(c); +} \ No newline at end of file