包装的malloc - Ç [英] Wrapping malloc - C
问题描述
我在C.初学者在阅读Git的源$ C $ C,我发现周围的的malloc
。
无效*的xmalloc(为size_t大小)
{
void *的RET =的malloc(大小);
如果(RET&安培;!&安培;!大小)
RET = malloc的(1);
如果(!RET){
release_pack_memory(大小,-1);
RET =的malloc(大小);
如果(RET&安培;!&安培;!大小)
RET = malloc的(1);
如果(!RET)
死(内存不足,malloc的失败);
}
#IFDEF XMALLOC_POISON
memset的(RET,0xA5的,大小);
#万一
返回RET;
}
问题
- 我不能,为什么他们使用理解
的malloc(1)
? - 这是什么
release_pack_memory
不和我找不到在整个源$ C $ C此功能的实现。 - 什么的
#IFDEF XMALLOC_POISON memset的(RET,0xA5的,大小);
确实
我打算重用我的项目这个功能。这是围绕的malloc
?
任何帮助将是巨大的。
-
的malloc(0)不能在所有一个平台上,在这种情况下,一个一字节的分配,而不是做工作。允许的长度为0的存储器块的分配简化程序的高层次逻辑
-
不知道。
-
通过与一个非零值填充所分配的内存,它是比较容易找到程序中的错误,其中所述存储器是没有适当的初始化中使用:程序将几乎立即崩溃在这种情况下。作为填充记忆需要时间,它被包裹在preprocessor定义,因此被期望只有当编译。
I am a beginner in C. While reading git's source code, I found this wrapper function around malloc
.
void *xmalloc(size_t size)
{
void *ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret) {
release_pack_memory(size, -1);
ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret)
die("Out of memory, malloc failed");
}
#ifdef XMALLOC_POISON
memset(ret, 0xA5, size);
#endif
return ret;
}
Questions
- I couldn't understand why are they using
malloc(1)
? - What does
release_pack_memory
does and I can't find this functions implementation in the whole source code. - What does the
#ifdef XMALLOC_POISON memset(ret, 0xA5, size);
does?
I am planning to reuse this function on my project. Is this a good wrapper around malloc
?
Any help would be great.
malloc(0) does not work on all a platforms, in which case a one-byte allocation is made instead. Allowing the allocation of 0-length memory blocks simplifies the higher-level logic of the program.
Don't know.
By filling the allocated memory with a non-zero value, it is easier to find bugs in the program where the memory is used without proper initialization: the program will crash almost immediately in such cases. As filling the memory takes time, it is wrapped in a preprocessor define, so it is compiled in only when desired.
这篇关于包装的malloc - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!