Когда блоки памяти выделяются функциями calloc(), malloc() или realloc(), функция free() библиотеки C используется для освобождения или освобождения блоков памяти, чтобы уменьшить их потери.
Функция free() в C должна использоваться только для указателей, указывающих на память, выделенную с помощью malloc(), или для указателя NULL. Функция free() только освобождает память из кучи и не вызывает деструктор. Чтобы уничтожить выделенную память и вызвать деструктор, мы можем использовать оператор delete() в C.
Синтаксис использования функции free() в C
void free(void *ptr)
Здесь ptr — это блок памяти, который необходимо освободить или освободить.
Например, программа 1 демонстрирует, как использовать free() с calloc() в C, а программа 2 демонстрирует, как использовать free() с malloc() в C.
Программа 1:
С
// C program to demonstrate use of
// free() function using calloc()
#include <stdio.h>
#include <stdlib.h>
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"
, 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 \n"
);
exit
(0);
}
// Memory has been Successfully allocated using calloc()
printf
(
"Successfully allocated the memory using calloc(). \n"
);
// Free the memory
free
(ptr);
printf
(
"Calloc Memory Successfully freed."
);
return
0;
}
Выход
Enter number of Elements: 5 Successfully allocated the memory using calloc(). Calloc Memory Successfully freed.
Программа 2:
С
// C program to demonstrate use of
// free() function using malloc()
#include <stdio.h>
#include <stdlib.h>
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"
, 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 \n"
);
exit
(0);
}
// Memory has been Successfully allocated using malloc()
printf
(
"Successfully allocated the memory using malloc(). \n"
);
// Free the memory
free
(ptr);
printf
(
"Malloc Memory Successfully freed."
);
return
0;
}
Выход
Enter number of Elements: 5 Successfully allocated the memory using malloc(). Malloc Memory Successfully freed.