yohhoyの日記

技術的メモをしていきたい日記

malloc(0)の振る舞い

C標準ライブラリ提供の malloc関数 に対して、メモリ確保サイズ 0 指定時の振る舞いは処理系定義(implementation defined)。realloc, calloc, aligned_alloc*1でも同様。
2021-09-09追記:次期C2x(C23)標準ライブラリreallocではメモリ確保サイズ 0 の指定は廃止予定(→id:yohhoy:20210909)。

ただし、処理系の振る舞いは下記2種類のうちいずれかとなる。

  • [A] ヌルポインタ(NULL)を返す。
  • [B] 有効なポインタ値を返す。ただしポインタが指す先へはアクセスできない。

C99(N1256) 7.20.3/p1より一部引用。C11(N1570)でも同様。

(snip) If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

メモ:というわけで、下記コードはwell-defined。

#include <stdlib.h>
int main()
{
  free(malloc(0));  // OK
  return 0;
}

関連URL

*1:C11標準ライブラリから追加された、アライメント指定付き動的メモリ確保関数。