【发布时间】:2020-03-20 22:30:18
【问题描述】:
实际上,我预计这里会出现警告/错误,但它编译时没有任何问题。为什么可以调用具有 0 个对象作为第一个参数的 calloc 函数?为什么要为此分配内存?
int* p_integer=calloc(0, sizeof(int));
if(!p_integer){
exit(EXIT_FAILURE);
}
//prints 4
printf("size *p_integer: %zu\n", sizeof(*p_integer));
好的,补充一点:
void* calloc( size_t num, size_t size );
Allocates memory for an array of num objects of size and initializes all bytes in the
allocated storage to zero.
If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated
memory block that is suitably aligned for any object type.
If size is zero, the behavior is implementation defined (null pointer may be returned,
or some non-null pointer may be returned that may not be used to access storage)
https://en.cppreference.com/w/c/memory/calloc
如何理解?就我而言,大小(第二个参数)不为零,对吗?因此,如果第一个参数 == 零,则无法解释这种情况。还是我必须计算 0*sizeof(int) == 0 (请求的内存块的大小)。它们是指哪个“尺寸”?
【问题讨论】:
-
由于
p_integer是int*类型,sizeof(*p_integer)与sizeof(int)相同。设置p_integer = NULL;不会改变p_integer的size。 -
malloc(0)或calloc(0, ...);可能会返回NULL指针或非 NULL 指针。在这两种情况下:不能使用内存并且返回指针上的free()是有效操作。 -
所以程序应该在 p_integer=NULL 之后退出; ?但事实并非如此。
-
编译器不需要为此发出警告。这可能会很有趣:stackoverflow.com/questions/1073157/zero-size-malloc
-
所以程序应该在 p_integer=NULL 之后退出:它取决于实现。
标签: c