logo

C ライブラリの free() 関数と例

C の free() 関数 動的に割り当てられたメモリを解放または割り当て解除するために使用され、メモリの無駄を減らすのに役立ちます。の Cフリー() この関数を使用して、静的に割り当てられたメモリ (ローカル変数など) やスタック上に割り当てられたメモリを解放することはできません。これは、malloc()、calloc()、realloc() 関数を使用して以前に割り当てられたヒープ メモリの割り当てを解除するためにのみ使用できます。

free() 関数は内部で定義されています ヘッダファイル。



Cライブラリのfree()関数

C free() 関数

C の free() 関数の構文

void free (void * ptr );>

パラメーター

    ptr は、解放または割り当て解除が必要なメモリ ブロックへのポインタです。

戻り値

  • free() 関数は値を返しません。

free() の例

例 1:

次の C プログラムは、 calloc() メモリを動的に割り当てる機能と、 無料() その記憶を解放する機能。

C




YouTubeビデオをvlcでダウンロード





// 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


RSAのアルゴリズム



// 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.>