为什么定义了malloc(0)实现的返回值? [英] Why is the return value of malloc(0) implementation-defined?

查看:70
本文介绍了为什么定义了malloc(0)实现的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ISO/IEC 9899:TC2(即C99标准),第7.20.3条规定:

ISO/IEC 9899:TC2 (i.e. the C99 standard), §7.20.3 states:

如果请求的空间大小为零,则行为是实现定义的:返回一个空指针,或者行为就像大小是某个非零值,不同之处在于返回的指针不得用于访问对象.

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.

换句话说,malloc(0)可能返回NULL或我不能取消引用的有效指针.

In other words, malloc(0) may either return NULL or a valid pointer which I may not dereference.

此行为背后的原因是什么?
而且,仅仅定义malloc(0)导致UB会更容易吗?

What is the rationale behind this behavior?
And wouldn't it be easier to just define that malloc(0) leads to UB?

推荐答案

C99原理(PDF链接)讨论了内存管理功能(来自C99 7.20.3)并解释:

The C99 Rationale (PDF link) discusses the memory management functions (from C99 7.20.3) and explains:

在这些函数的定义中对空指针和零长度分配请求的处理在某种程度上受到了支持这种范例的渴望的指导:

The treatment of null pointers and zero-length allocation requests in the definition of these functions was in part guided by a desire to support this paradigm:

OBJ * p; // pointer to a variable list of OBJs
    /* initial allocation */
p = (OBJ *) calloc(0, sizeof(OBJ)); 
    /* ... */
    /* reallocations until size settles */
while(1) { 
    p = (OBJ *) realloc((void *)p, c * sizeof(OBJ)); 
      /* change value of c or break out of loop */
} 

据报道,这种编码风格不一定得到委员会的认可,并且得到了广泛使用.

This coding style, not necessarily endorsed by the Committee, is reported to be in widespread use.

某些实现为零字节分配请求返回了非null值.
尽管此策略具有在理论上区分什么都没有"和零"(未分配的指针与指向零长度空间的指针)的理论优势,但它具有更引人注目的理论上的缺点,即需要零长度对象的概念.

Some implementations have returned non-null values for allocation requests of zero bytes.
Although this strategy has the theoretical advantage of distinguishing between "nothing" and "zero" (an unallocated pointer vs. a pointer to zero-length space), it has the more compelling theoretical disadvantage of requiring the concept of a zero-length object.

由于无法声明此类对象库,因此它们存在的唯一途径就是通过此类分配请求.

Since such objects Library cannot be declared, the only way they could come into existence would be through such allocation requests.

C89委员会决定不接受零长度对象的想法.分配因此,函数可能会为零字节的分配请求返回空指针.注意,这种处理并不排除上面概述的范例.

The C89 Committee decided not to accept the idea of zero-length objects. The allocation functions may therefore return a null pointer for an allocation request of zero bytes. Note that this treatment does not preclude the paradigm outlined above.

C89中的安静更改:依赖大小为零的分配请求返回非空指针的程序的行为会有所不同.

QUIET CHANGE IN C89: A program which relies on size-zero allocation requests returning a non-null pointer will behave differently.

这篇关于为什么定义了malloc(0)实现的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆