Dynamic memory: malloc, free, and realloc · Mémoire dynamique : malloc, free, et realloc
Stack memory vs heap memory
- Normal local variables live on the stack. They appear when a function starts and vanish when it returns.
- Sometimes you need memory that outlives the function, or whose size you only know at run time.
- That memory comes from the heap. You ask for it, and later you give it back.
Mémoire pile vs mémoire tas
- Les variables locales normales vivent sur la pile. Elles apparaissent quand une fonction commence et disparaissent quand elle retourne.
- Parfois, vous avez besoin d'une mémoire qui survit à la fonction, ou dont la taille n'est connue qu'à l'exécution.
- Cette mémoire vient du tas. Vous la demandez, et plus tard vous la rendez.
malloc and sizeof
mallocasks the heap for a block of bytes and returns a pointer to it.- Use
sizeofto get the size of one item:malloc(n * sizeof(int))makes room fornints. - The block is yours to use through the pointer, exactly like an array:
a[0],a[1], ...
malloc et sizeof
mallocdemande au tas un bloc d'octets et retourne un pointeur vers celui-ci.- Utilisez
sizeofpour obtenir la taille d'un élément :malloc(n * sizeof(int))fait de la place pournints. - Le bloc vous appartient et vous l'utilisez via le pointeur, exactement comme un tableau :
a[0],a[1], ...
free and memory leaks
- When you are done with heap memory, give it back with
free(pointer). - If you never
freeit, the program leaks memory — it holds space it no longer uses. - Rule for these tasks: your function allocates and returns; the checker frees it. Do not call
freeyourself.
free et fuites de mémoire
- Quand vous avez fini avec la mémoire tas, rendez-la avec
free(pointer). - Si vous ne la
freejamais, le programme fuit de la mémoire — il garde de la place qu'il n'utilise plus. - Règle pour ces exercices : votre fonction alloue et retourne ; le vérificateur la libère. N'appeler pas
freevous-même.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(3 * sizeof(int)); // room for 3 ints
a[0] = 5; a[1] = 6; a[2] = 7;
printf("%d\n", a[0] + a[1] + a[2]); // 18
free(a); // give it back
return 0;
}
Growing an array with realloc
realloc(a, newSize)resizes a heap block, keeping the old contents.- It may move the block, so always use its return value:
a = realloc(a, ...). - This is how you grow an array one item at a time, like a list that gets longer.
Grandir un tableau avec realloc
realloc(a, newSize)redimensionne un bloc tas, gardant le contenu ancien.- Il peut déplacer le bloc, donc utilisez toujours sa valeur de retour :
a = realloc(a, ...). - C'est ainsi que vous grandissez un tableau élément par élément, comme une liste qui s'allonge.
Common mistakes
- Every
mallocneeds a matchingfree; do not use memory afterfree. - Check that
mallocdid not returnNULL.
Erreurs courantes
- Chaque
malloca unfreecorrespondant ; n'utilisez pas la mémoire aprèsfree. - Vérifiez que
mallocn'a pas retournéNULL.
Now you try
- Use
malloc(n * sizeof(int))for new arrays, and#include <stdlib.h>. - Your function returns the pointer; the checker frees it — do not call
free. Do not write amain.
À vous maintenant
- Utilisez
malloc(n * sizeof(int))pour de nouveaux tableaux, et#include <stdlib.h>. - Votre fonction retourne le pointeur ; le vérificateur la libère — ne pas appeler
free. Ne pas écrire unmain.
Complete int *make_array(int n, int value) so it allocates n ints (with malloc), sets every one to value, and returns the pointer. The checker frees it. Do not · non write a main. · Complétez int *make_array(int n, int value) pour qu'il alloue n entiers (avec malloc), définisse chacun à value, et retourne le pointeur. Le vérificateur le libère. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete int *concat(const int a[], int na, const int b[], int nb) so it allocates na + nb ints, copies all of a then all of b, and returns the pointer. The checker frees it. Do not · non write a main. · Complétez int *concat(const int a[], int na, const int b[], int nb) pour qu'il alloue na + nb entiers, copie tout de a puis tout de b, et retourne le pointeur. Le vérificateur le libère. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete int *push(int *a, int *len, int value) so it grows the heap array a to hold one more int with realloc, stores value at the end, increases *len by 1, and returns the new pointer. The checker frees it. Do not · non write a main. · Complétez int *push(int *a, int *len, int value) pour qu'il agrandisse le tableau heap a pour contenir un entier de plus avec realloc, stocke value à la fin, incrémente *len de 1, et retourne le nouveau pointeur. Le vérificateur le libère. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.