使用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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...