-1

代码:

typedef long Align;
union header {
        struct {
                union header *ptr;
                unsigned size;
        } s;
        Align x;
};

typedef union header Header;

................
................
................

static Header *morecore(unsigned nu)
{
        char *cp, *sbrk(int);
        Header *up;
        if (nu < NALLOC)
                nu = NALLOC;
        cp = sbrk(nu * sizeof(Header));
        if (cp == (char *) -1)
                return NULL;
        up = (Header *) cp;
        up->s.size = nu;
        free((void *)(up+1));
        return freep;
}

怀疑:

考虑 morecore 函数从其他函数调用并从参数(nu)接收 4 作为 int。我对以下陈述有疑问。

cp = sbrk(nu * sizeof(Header));
if (cp == (char *) -1)
        return NULL;
up = (Header *) cp;
up->s.size = nu;

up 只是一个指向 Header 的指针。但是,它仍然没有指向任何 Header 变量。sbrk 分配请求的内存并返回当前程序中断并将其存储在 cp 中。然后将存储在cp中的地址强制转换并分配给up。现在, up 包含由 sbrk 作为指向 Header 变量的指针返回的地址。然后出现以下语句,

up->s.size = nu;

up仅包含 sbrk 返回的地址。那么上面的语句如何将 nu 存储在 size 变量中。

4

1 回答 1

0
// sbrk allocate "nu * sizeof(Header)" bytes at the address returned in cp.
cp = sbrk(nu * sizeof(Header));
// if cp is set to error return value (void *)-1 then cp is an invalid address.
if (cp == (char *) -1)
        return NULL;
// up is a pointer and its value is set to the new address (cp).
up = (Header *) cp;
// up is set to the new data allocated by sbrk in the memory. "->" will resolve the address in "up" and store the data.
up->s.size = nu;
于 2015-07-15T13:10:26.587 回答