De free() funksjon i C brukes til å frigjøre eller deallokere det dynamisk tildelte minnet og hjelper til med å redusere minnesvinn. De C gratis() funksjonen kan ikke brukes til å frigjøre det statisk tildelte minnet (f.eks. lokale variabler) eller minne tildelt på stabelen. Den kan bare brukes til å deallokere heap-minnet som tidligere er allokert ved å bruke malloc(), calloc() og realloc() funksjoner.
Free()-funksjonen er definert inne header-fil.

C free() funksjon
Syntaks for free()-funksjonen i C
void free (void * ptr );>
Parametere
- ptr er pekeren til minneblokken som må frigjøres eller deallokeres.
Returverdi
- Free()-funksjonen returnerer ingen verdi.
Eksempler på gratis()
Eksempel 1:
Følgende C-program illustrerer bruken av calloc() funksjon for å tildele minne dynamisk og gratis() funksjon for å frigjøre det minnet.
C
betinget operatør i 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;> }> |
>
>Produksjon
Enter number of Elements: 5 Successfully allocated the memory using calloc(). Calloc Memory Successfully freed.>
Eksempel 2:
Følgende C-program illustrerer bruken av malloc() funksjon for å tildele minne dynamisk og gratis() funksjon for å frigjøre det minnet.
C
// 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;> }> |
>
>
hvordan deaktiverer utviklermodusProduksjon
Enter number of Elements: 5 Successfully allocated the memory using malloc(). Malloc Memory Successfully freed.>