加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用malloc(0)和memcpy

发布时间:2020-12-16 03:22:00 所属栏目:百科 来源:网络整理
导读:我在某处读到:取消引用由大小为零的“新”分配返回的指针是UB. 在C中是否相同? 如果是,是以下代码UB? (假设大小= 0) a-object[index].data = malloc(size); memcpy(a-object[index].data,bytes,size); 据我了解:不.只是想仔细检查一下. 解决方法 当您将0
我在某处读到:取消引用由大小为零的“新”分配返回的指针是UB.
在C中是否相同?
如果是,是以下代码UB? (假设大小= 0)
a->object[index].data = malloc(size);  
 memcpy(a->object[index].data,bytes,size);

据我了解:不.只是想仔细检查一下.

解决方法

当您将0作为参数传递给malloc时,它将分配的内存释放到malloc返回的指针.

结果是实现定义的.

C11:7.22.3内存管理功能:

[…] 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.

标准也说:

The free function causes the space pointed to by ptr to be deallocated,that is,made available for further allocation. If ptr is a null pointer,no action occurs.

因此,在实现定义行为的任??何一种情况下,释放都不会调用未定义的行为.

现在转到问题的另一部分.

7.1.4库函数的使用:

If an argument to a function has an invalid value (such as a value
outside the domain of the function,or a pointer outside the address space of the program,
or a null pointer,or a pointer to non-modifiable storage when the corresponding
parameter is not const-qualified) or a type (after promotion) not expected by a function
with variable number of arguments,the behavior is undefined.

C11:7.24.1 p(2):

Where an argument declared as size_t n specifies the length of the array for a
function,n can have the value zero on a call to that function. Unless explicitly stated
otherwise in the description of a particular function in this subclause,pointer arguments on such a call shall still have valid values,as described in 7.1.4. On such a call,a function that locates a character finds no occurrence,a function that compares two character sequences returns zero,and a function that copies characters copies zero characters.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读