K&安培; - [R的malloc code没有意义? [英] K & R malloc code doesn't make sense?
问题描述
这code是从K&放大器; - [R书 - 第8章第7节:举例 - 存储分配器。这code,至少对我来说,没有任何意义。 头是一个结构和最严格的对齐类型,这是一个长型的联合。然后的malloc会发现头部大小的倍数的大小足够大的自由空间。
This code is from the K & R book - Chapter 8 Section 7: Example - Storage Allocator. This code, at least for me, doesn't make sense. "Header" is a union of a struct and a "most restrictive alignment type", which is a long type. Malloc will then find a big enough free space with size of a multiple of the header size.
static Header base; /* empty list to get started */
static Header *freep = NULL; /* start of free list */
/* malloc: general-purpose storage allocator */
void *malloc(unsigned nbytes)
{
Header *p, *prevp;
Header *morecore(unsigned);
unsigned nunits;
nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;
if ((prevp = freep) == NULL) { /* no free list yet */
base.s.ptr = freeptr = prevptr = &base;
base.s.size = 0;
}
for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) {
if (p->s.size >= nunits) { /* big enough */
if (p->s.size == nunits) /* exactly */
prevp->s.ptr = p->s.ptr;
else { /* allocate tail end */
p->s.size -= nunits;
p += p->s.size;
p->s.size = nunits;
}
freep = prevp;
return (void *)(p+1);
}
if (p == freep) /* wrapped around free list */
if ((p = morecore(nunits)) == NULL)
return NULL; /* none left */
}
}
这code的奇数部分是语句 nunits =(为nbytes +的sizeof(头)-1)/的sizeof(头)+ 1;
这是那么在比较中使用如果(对GT; s.size> = nunits)
来找到一台足够大的空间,在头的规模而言。应该不是前者是 nunits =(为nbytes +的sizeof(头))/的sizeof(标题)
只?原来的code将评估为低于它应该是一个值。什么是与+ -1s?为什么分配空间小于期望。
The odd part of this code is the statement nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;
which is then used in the comparison if (p->s.size >= nunits)
to find a big enough space with units in terms of the size of Header. Shouldn't the former be nunits = (nbytes+sizeof(Header)) / sizeof(Header)
only? The original code would evaluate to a value less than it ought to be. What is with the +-1s? Why allocate space less than the desired.
推荐答案
的 1
和 +1
是考虑到不属于该块大小的相乘值。
The -1
and +1
are to account for values that aren't multiplies of the block size.
例如,假设块的大小是10,如果你尝试使用公式 N / 10
来获得所需的块数,那么你将获得1块N = 15,这是不对的,你需要2。
For example, suppose the block size is 10. If you try to use the formula n / 10
to get the number of required blocks then you would get 1 block for n = 15. This is wrong, you need 2.
如果您更改公式为 N / 10 + 1
那么它也将是错误的。当n = 20你只需要2个街区,但公式将返回3。
If you change the formula to be n / 10 + 1
then it will also be wrong. When n = 20 you only need 2 blocks, but that formula will return 3.
正确的公式是(N - 1)/ 10 + 1
。这就是你怎么收尾整数除法。与此唯一的区别,你问公式是额外的的sizeof(标题)
,这是刚需的头本身。
The correct formula is (n - 1) / 10 + 1
. That's how you round up with integer division. The only difference with this and the formula you asked about is the extra sizeof(Header)
, which is just the extra space needed for the header itself.
这篇关于K&安培; - [R的malloc code没有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!