logo

malloc()、calloc()、free()、realloc() を使用した C での動的メモリ割り当て

C は構造化言語であるため、プログラミングにはいくつかの固定ルールがあります。その 1 つに、配列のサイズの変更が含まれます。配列は、連続したメモリ位置に格納されている項目のコレクションです。

配列



ご覧のとおり、上記の配列の長さ (サイズ) は 9 です。しかし、この長さ (サイズ) を変更する必要がある場合はどうなるでしょうか?例えば、

  • この配列に 5 つの要素のみを入力する必要がある場合。この場合、残りの 4 つのインデックスはこの配列内のメモリを浪費しているだけです。したがって、配列の長さ (サイズ) を 9 から 5 に減らす必要があります。
  • 別の状況を考えてみましょう。この例には、9 つ​​のインデックスがすべて入力された 9 つの要素の配列があります。ただし、この配列にはさらに 3 つの要素を入力する必要があります。この場合、さらに 3 つのインデックスが必要になります。したがって、配列の長さ (サイズ) を 9 から 12 に変更する必要があります。

この手順は次のように呼ばれます C での動的メモリ割り当て
したがって、C 動的メモリ割り当て データ構造 (配列など) のサイズが実行時に変更されるプロシージャとして定義できます。
C には、これらのタスクを達成するためのいくつかの関数が用意されています。 C によって提供される 4 つのライブラリ関数が次のように定義されています。 ヘッダー ファイルを使用して、C プログラミングでの動的なメモリ割り当てを容易にします。彼らです:

  1. malloc()
  2. calloc()
  3. 無料()
  4. realloc()

それぞれを詳しく見てみましょう。



Cのmalloc()メソッド

マロック または メモリ割り当て C のメソッドは、指定されたサイズの単一の大きなメモリ ブロックを動的に割り当てるために使用されます。これは、任意の形式のポインターにキャストできる void 型のポインターを返します。実行時にメモリを初期化しないため、最初はデフォルトのガベージ値で各ブロックが初期化されます。

C の malloc() の構文

ptr = (cast-type*) malloc(byte-size)   For Example:>

ptr = (int*) malloc(100 * sizeof(int));
int のサイズは 4 バイトであるため、このステートメントは 400 バイトのメモリを割り当てます。また、ポインタ ptr は、割り当てられたメモリの最初のバイトのアドレスを保持します。



スペースが不十分な場合、割り当ては失敗し、NULL ポインタが返されます。

C での malloc() の例

C




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >printf>(>'Enter number of elements:'>);> >scanf>(>'%d'>,&n);> >printf>(>'Entered number of elements: %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);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

蜂の巣とは何ですか

>

>

出力

Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>

Cのcalloc()メソッド

  1. コールク または 連続割り当て C のメソッドは、指定されたタイプの指定された数のメモリ ブロックを動的に割り当てるために使用されます。これは malloc() とよく似ていますが、次の 2 つの異なる点があります。
  2. 各ブロックをデフォルト値「0」で初期化します。
  3. malloc() と比較して、2 つのパラメータまたは引数があります。

C の calloc() の構文

ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>

例えば:

ptr = (float*) calloc(25, sizeof(float));
このステートメントは、それぞれが浮動小数点のサイズを持つ 25 個の要素に対してメモリ内の連続した領域を割り当てます。

スペースが不十分な場合、割り当ては失敗し、NULL ポインタが返されます。

C での calloc() の例

C




CSSテキストの整列

#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %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);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

>

>

出力

Cのフィボナッチ数列
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>

Cのfree()メソッド

無料 C のメソッドは動的に使用されます。 割り当てを解除する 想い出。関数 malloc() および calloc() を使用して割り当てられたメモリは、単独では割り当て解除されません。したがって、動的メモリ割り当てが行われるときは常に、free() メソッドが使用されます。メモリを解放することで、メモリの無駄を減らすことができます。

C の free() の構文

free(ptr);>

C での free() の例

C




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int> *ptr, *ptr1;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d '>, n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Dynamically allocate memory using calloc()> >ptr1 = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL || ptr1 == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc. '>);> >// Free the memory> >free>(ptr);> >printf>(>'Malloc Memory successfully freed. '>);> >// Memory has been successfully allocated> >printf>(>' Memory successfully allocated using calloc. '>);> >// Free the memory> >free>(ptr1);> >printf>(>'Calloc Memory successfully freed. '>);> >}> >return> 0;> }>

>

>

出力

Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>

Cのrealloc()メソッド

再ロック または 再割り当て C のメソッドは、以前に割り当てられたメモリのメモリ割り当てを動的に変更するために使用されます。言い換えれば、malloc または calloc を使用して以前に割り当てられたメモリが不十分な場合、realloc を使用して次のことができます。 メモリを動的に再割り当てする 。メモリの再割り当てにより、すでに存在する値が維持され、新しいブロックはデフォルトのガベージ値で初期化されます。

C の realloc() の構文

ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

スペースが不十分な場合、割り当ては失敗し、NULL ポインタが返されます。

C での realloc() の例

C




BFSとDFS
#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d '>, n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } // Get the new size for the array n = 10; printf(' Enter the new size of the array: %d ', n); // Dynamically re-allocate memory using realloc() ptr = (int*)realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf('Memory successfully re-allocated using realloc. '); // Get the new elements of the array for (i = 5; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } free(ptr); } return 0; }>

>

>

出力

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,>

realloc() メソッドの別の例は次のとおりです。

C




#include> #include> int> main()> {> >int> index = 0, i = 0, n,> >*marks;>// this marks pointer hold the base address> >// of the block created> >int> ans;> >marks = (>int>*)>malloc>(>sizeof>(> >int>));>// dynamically allocate memory using malloc> >// check if the memory is successfully allocated by> >// malloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >// memory has successfully allocated> >printf>(>'Memory has been successfully allocated by '> >'using malloc '>);> >printf>(>' marks = %pc '>,> >marks);>// print the base or beginning> >// address of allocated memory> >do> {> >printf>(>' Enter Marks '>);> >scanf>(>'%d'>, &marks[index]);>// Get the marks> >printf>(>'would you like to add more(1/0): '>);> >scanf>(>'%d'>, &ans);> >if> (ans == 1) {> >index++;> >marks = (>int>*)>realloc>(> >marks,> >(index + 1)> >*>sizeof>(> >int>));>// Dynamically reallocate> >// memory by using realloc> >// check if the memory is successfully> >// allocated by realloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >printf>(>'Memory has been successfully '> >'reallocated using realloc: '>);> >printf>(> >' base address of marks are:%pc'>,> >marks);>////print the base or> >///beginning address of> >///allocated memory> >}> >}> >}>while> (ans == 1);> >// print the marks of the students> >for> (i = 0; i <= index; i++) {> >printf>(>'marks of students %d are: %d '>, i,> >marks[i]);> >}> >free>(marks);> >}> >return> 0;> }>

>

>

マックオペレーティングシステム

出力: