The funcția free() în C este folosit pentru a elibera sau dezaloca memoria alocată dinamic și ajută la reducerea pierderii de memorie. The C gratuit() funcția nu poate fi utilizată pentru a elibera memoria alocată static (de exemplu, variabilele locale) sau memoria alocată pe stivă. Poate fi folosit doar pentru a dezaloca memoria heap alocată anterior folosind funcțiile malloc(), calloc() și realloc().
Funcția free() este definită în interior fișier antet.

Funcția C free().
Sintaxa funcției free() în C
void free (void * ptr );>
Parametrii
- ptr este indicatorul către blocul de memorie care trebuie eliberat sau dealocat.
Valoare returnată
- Funcția free() nu returnează nicio valoare.
Exemple de free()
Exemplul 1:
Următorul program C ilustrează utilizarea calloc() funcţie de alocare dinamică a memoriei şi gratuit() funcția de a elibera acea memorie.
C
cum se citește fișierul csv în java
// C program to demonstrate use of> // free() function using calloc()> #include> #include> int> main()> {> >// This pointer ptr will hold the> >// base address of the block created> >int>* ptr;> >int> n = 5;> >// Get the number of elements for the array> >printf>(>'Enter number of Elements: %d
'>, n);> >scanf>(>'%d'>, &n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by calloc() or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated
'>);> >exit>(0);> >}> >// Memory has been Successfully allocated using calloc()> >printf>(>'Successfully allocated the memory using '> >'calloc().
'>);> >// Free the memory> >free>(ptr);> >printf>(>'Calloc Memory Successfully freed.'>);> >return> 0;> }> |
>
>Ieșire
Enter number of Elements: 5 Successfully allocated the memory using calloc(). Calloc Memory Successfully freed.>
Exemplul 2:
Următorul program C ilustrează utilizarea malloc() funcţie de alocare dinamică a memoriei şi gratuit() funcția de a elibera acea memorie.
C
șir de matrice java
// C program to demonstrate use of> // free() function using malloc()> #include> #include> int> main()> {> >// This pointer ptr will hold the> >// base address of the block created> >int>* ptr;> >int> n = 5;> >// Get the number of elements for the array> >printf>(>'Enter number of Elements: %d
'>, n);> >scanf>(>'%d'>, &n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc() or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated
'>);> >exit>(0);> >}> >// Memory has been Successfully allocated using malloc()> >printf>(>'Successfully allocated the memory using '> >'malloc().
'>);> >// Free the memory> >free>(ptr);> >printf>(>'Malloc Memory Successfully freed.'>);> >return> 0;> }> |
>
>Ieșire
Enter number of Elements: 5 Successfully allocated the memory using malloc(). Malloc Memory Successfully freed.>