Easy Tutorial
❮ C Exercise Example78 C Exercise Example49 ❯

C Library Function - free()

C Standard Library - <stdlib.h>

Description

The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

Declaration

Here is the declaration for the free() function.

void free(void *ptr)

Parameters

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the free() function.

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

int main()
{
   char *str;

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

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

   /* Free the allocated memory */
   free(str);

   return(0);
}

Let's compile and run the above program, which will produce the following result:

String = tutorialpro,  Address = 0x7fe4e4c02b10
String = tutorialpro.org,  Address = 0x7fe4e4c02b10

C Standard Library - <stdlib.h>

❮ C Exercise Example78 C Exercise Example49 ❯