yohhoyの日記

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

realloc(ptr, 0)は廃止予定

C標準ライブラリrealloc関数に対して、サイズ0を指定すべきでない。

realloc(ptr, 0)によってptrが指すメモリブロックが解放(free(ptr)相当)される保証はない。この動作は ISO C および POSIX それぞれで明言されている。JPCERT MEM04-C サイズ0のメモリ割り当てを行わない も参照のこと。

C標準ライブラリ仕様に文面解釈の幅があったため処理系ごとに動作が異なる状況となっており、次期C2x(C23)標準ライブラリでは「reallocへのサイズ0指定」は廃止予定の機能(obsolescent feature)とされる。これ以外の挙動については現行C17と同じ。

C90/C99/C11仕様

C11 7.22.3.5/p2より引用。C90 7.10.3, C99 7.20.3.4/p2も同一文面。

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

C17仕様

C17 7.22.3.5/p3より引用(下線部は強調)。

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If size is nonzero and memory for the new object is not allocated, the old object is not deallocated. If size is zero and memory for the new object is not allocated, it is implementation-defined whether the old object is deallocated. If the old object is not deallocated, its value shall be unchanged.

C2x仕様

C2x WD(N2596) 7.22.3.5/p3, 7.31.14/p2より引用(下線部は強調)。

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, or if the size is zero, the behavior is undefined. If memory for the new object is not allocated, the old object is not deallocated and its value is unchanged.

Invoking realloc with a size argument equal to zero is an obsolescent feature.

POSIX仕様(2017)

IEEE Std 1003.1-2017より一部引用。FUTURE DIRECTIONS(informative)節にてWG14 C2x標準化ステータスへの言及あり。

DESCRIPTION
(snip) If the size of the space requested is zero, the behavior shall be implementation-defined: either a null pointer is returned, or the behavior shall be as if the size were some non-zero value, except that the behavior is undefined if the returned pointer is used to access an object. If the space cannot be allocated, the object shall remain unchanged.
(snip)

FUTURE DIRECTIONS(informative)
This standard defers to the ISO C standard. While that standard currently has language that might permit realloc (p, 0), where p is not a null pointer, to free p while still returning a null pointer, the committee responsible for that standard is considering clarifying the language to explicitly prohibit that alternative.

関連URL