그만큼 C의 free() 함수 동적으로 할당된 메모리를 해제하거나 할당 해제하는 데 사용되며 메모리 낭비를 줄이는 데 도움이 됩니다. 그만큼 C무료() 함수는 정적으로 할당된 메모리(예: 지역 변수)나 스택에 할당된 메모리를 해제하는 데 사용할 수 없습니다. malloc(), calloc() 및 realloc() 함수를 사용하여 이전에 할당된 힙 메모리를 할당 해제하는 데에만 사용할 수 있습니다.
free() 함수는 내부에 정의되어 있습니다. 헤더 파일.

C free() 함수
C의 free() 함수 구문
void free (void * ptr );>
매개변수
- ptr은 해제되거나 할당 해제되어야 하는 메모리 블록에 대한 포인터입니다.
반환 값
- free() 함수는 어떤 값도 반환하지 않습니다.
free()의 예
예시 1:
다음 C 프로그램은 콜록() 동적으로 메모리를 할당하는 함수 무료() 해당 메모리를 해제하는 기능입니다.
씨
문자열.하위 문자열 자바
// 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;> }> |
>
>산출
Enter number of Elements: 5 Successfully allocated the memory using calloc(). Calloc Memory Successfully freed.>
예 2:
다음 C 프로그램은 malloc() 동적으로 메모리를 할당하는 함수 무료() 해당 메모리를 해제하는 기능입니다.
씨
자바스크립트로 자다
// 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;> }> |
>
>산출
Enter number of Elements: 5 Successfully allocated the memory using malloc(). Malloc Memory Successfully freed.>