使用malloc(0)和memcpy

前端之家收集整理的这篇文章主要介绍了使用malloc(0)和memcpy前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在某处读到:取消引用由大小为零的“新”分配返回的指针是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.

猜你在找的C&C++相关文章