Funzione libreria C - free ()

Descrizione

La funzione di libreria C. void free(void *ptr) dealloca la memoria precedentemente allocata da una chiamata a calloc, malloc o realloc.

Dichiarazione

Di seguito è riportata la dichiarazione per la funzione free ().

void free(void *ptr)

Parametri

  • ptr- Questo è il puntatore a un blocco di memoria precedentemente allocato con malloc, calloc o realloc da deallocare. Se un puntatore nullo viene passato come argomento, non si verifica alcuna azione.

Valore di ritorno

Questa funzione non restituisce alcun valore.

Esempio

L'esempio seguente mostra l'utilizzo della funzione free ().

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   /* Deallocate allocated memory */
   free(str);
   
   return(0);
}

Compiliamo ed eseguiamo il programma sopra che produrrà il seguente risultato:

String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448