malloc() と calloc() の違いと例

機能 malloc() そして calloc() メモリを動的に割り当てるライブラリ関数です。動的とは、ランタイム (プログラムの実行) 中にヒープ セグメントからメモリが割り当てられることを意味します。

初期化

malloc() 指定されたサイズ (バイト単位) のメモリ ブロックを割り当て、ブロックの先頭へのポインタを返します。 malloc() は割り当てられたメモリを初期化しません。最初に初期化せずに割り当てられたメモリから読み取ろうとすると、未定義の動作が呼び出されます。これは通常、読み取った値がガベージ値になることを意味します。

calloc() メモリを割り当て、割り当てられたメモリ内のすべてのバイトを 0 に初期化します。初期化せずに割り当てられたメモリの値を読み取ろうとすると、calloc() によってすでに 0 に初期化されているため、0 が返されます。

パラメーター

malloc() は 1 つの引数を取ります。 割り当てるバイト数。

malloc() とは異なり、calloc() は 2 つの引数を取ります。

  1. 割り当てられるブロックの数。
  2. 各ブロックのバイト単位のサイズ。

戻り値

malloc() および calloc() での割り当てが成功すると、メモリのブロックへのポインタが返されます。それ以外の場合は、失敗を示す NULL が返されます。

以下の C コードは、動的メモリを割り当てる malloc 関数と calloc 関数の違いを示しています。

C




// C code that demonstrates the difference> // between calloc and malloc> #include> #include> int> main()> {> > // Both of these allocate the same number of bytes,> > // which is the amount of bytes that is required to> > // store 5 int values.> > // The memory allocated by calloc will be> > // zero-initialized, but the memory allocated with> > // malloc will be uninitialized so reading it would be> > // undefined behavior.> > int> * allocated_with_malloc => malloc> (5 *> sizeof> (> int> ));> > int> * allocated_with_calloc => calloc> (5,> sizeof> (> int> ));> > // As you can see, all of the values are initialized to> > // zero.> > printf> (> 'Values of allocated_with_calloc: '> );> > for> (> size_t> i = 0; i <5; ++i) {> > printf> (> '%d '> , allocated_with_calloc[i]);> > }> > putchar> (> ' '> );> > // This malloc requests 1 terabyte of dynamic memory,> > // which is unavailable in this case, and so the> > // allocation fails and returns NULL.> > int> * failed_malloc => malloc> (1000000000000);> > if> (failed_malloc == NULL) {> > printf> (> 'The allocation failed, the value of '> > 'failed_malloc is: %p'> ,> > (> void> *)failed_malloc);> > }> > // Remember to always free dynamically allocated memory.> > free> (allocated_with_malloc);> > free> (allocated_with_calloc);> }>

出力

Values of allocated_with_calloc: 0 0 0 0 0 The allocation failed, the value of failed_malloc is: (nil) 

C の malloc() と calloc() の違い

違いを表形式で見てみましょう。

はい・いいえ。

malloc()

calloc()

1.

malloc() は、固定サイズのメモリ ブロックを 1 つ作成する関数です。 calloc() は、指定された数のメモリ ブロックを 1 つの変数に割り当てる関数です。

2.

malloc() は引数を 1 つだけ取ります calloc() は 2 つの引数を取ります。

3.

malloc() は calloc よりも高速です。 calloc() は malloc() より遅い

4.

malloc() は時間効率が高い calloc() は時間効率が低い

5.

malloc() はメモリ割り当てを示すために使用されます calloc() は、連続したメモリ割り当てを示すために使用されます。

6.

構文 : void* malloc(size_t size); 構文 : void* calloc(size_t num, size_t size);

8.

malloc() はメモリをゼロに初期化しません calloc() はメモリをゼロに初期化します

9.

malloc() は余分なメモリ オーバーヘッドを追加しません calloc() はメモリのオーバーヘッドを追加します

関連記事