码:
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函数正在从其他函数调用,并从arguments(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。现在,包含
sbrk作为Header变量的指针返回的地址。然后出现以下语句,
up->s.size = nu;
up
仅包含sbrk返回的地址。然后上面的语句如何将nu存储在size变量中。 最佳答案
// 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;
关于c - sbrk函数和C程序中的指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31308342/