问题描述
我正在努力开发四个基本内存分配例程malloc
,realloc
,calloc
和free
(与Electric Fence的操作类似)的调试实现,以调试具有以下功能的嵌入式系统上的堆损坏:没有资源来运行其他内存调试工具,或者没有其他工具(例如,用于PowerPC的LynxOS 7.0随GCC 4.6.3一起提供,以及glibc和libstdc ++的专有实现,其中不包含mtrace
系列功能).
I am working to develop debug implementations of the four basic memory allocation routines malloc
, realloc
, calloc
, and free
(similar in operation to Electric Fence) to debug heap corruption on embedded systems which do not have the resources to run other memory debugging tools, or for which other tools do not exist (for instance, LynxOS 7.0 for PowerPC ships with GCC 4.6.3, and a proprietary implementation of glibc and libstdc++ which does not include the mtrace
family of functions).
以下是来自GCC的calloc.c的calloc的源代码.
The following is the source code for calloc, from calloc.c in GCC's libiberty.
PTR
calloc (size_t nelem, size_t elsize)
{
register PTR ptr;
if (nelem == 0 || elsize == 0)
nelem = elsize = 1;
ptr = malloc (nelem * elsize);
if (ptr) bzero (ptr, nelem * elsize);
return ptr;
}
如果nelem
和elsize
都等于1
,为什么都将它们设置为等于1
?
Why are nelem
and elsize
both set equal to 1
if either equals 0
?
如果我尝试分配大小为n
的0
块或大小为0
的n
块,则两种情况都不会导致总分配0
个总字节,而不是1
字节?
If I attempt to allocate 0
chunks of size n
or n
chunks with 0
size, wouldn't either case result in an aggregate allocation of 0
total bytes, and not 1
byte?
推荐答案
减少歧义.
calloc(0, x), calloc(x, 0), malloc(0)
成功时可能会返回NULL
或非NULL
指针.在这两种情况下,都不会取消引用指针而不会引起未定义行为(UB).
calloc(0, x), calloc(x, 0), malloc(0)
, when successful, may return NULL
or a non-NULL
pointer. In both cases, the pointer may not be de-referenced without causing undefined behavior (UB).
不成功时,返回NULL
指针.
通过确保分配大小大于0,在返回NULL
时没有歧义-从 this calloc()
分配失败.
By insuring the allocation size is more than 0, there is no ambiguity when NULL
is returned - the allocation failed from this calloc()
.
注意,更好的功能还可以检测产品溢出.
Note, a better function would also detect product overflow.
if (nelem == 0 || elsize == 0) {
nelem = elsize = 1;
} else if (SIZE_MAX/nelem > elsize) {
return NULL; // Too much for this implementation
}
...
我希望该项目的malloc(0)
还要确保未分配0字节.但是,简单地调用ptr = malloc (0); if (ptr) bzero (ptr, 0);
并不会将那1个字节分配为零. if (nelem == 0 || elsize == 0) nelem = elsize = 1;
确认分配至少为1个字节,并且将分配清零.
I'd expect the malloc(0)
of that project to also insure that 0 bytes are not allocated. Yet simply calling ptr = malloc (0); if (ptr) bzero (ptr, 0);
would not zero that 1 byte allocation. if (nelem == 0 || elsize == 0) nelem = elsize = 1;
makes certain the allocation is at least 1 byte and that allocation is zeroed.
这篇关于如果nelem或elsize == 0,为什么calloc分配1个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!