在C中是否相同?
如果是,是以下代码UB? (假设大小= 0)
a->object[index].data = malloc(size); memcpy(a->object[index].data,bytes,size);
据我了解:不.只是想仔细检查一下.
解决方法
结果是实现定义的.
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 byptr
to be deallocated,that is,made available for further allocation. Ifptr
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.
原文地址:https://www.jb51.cc/c/111682.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。