Code:
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;
}
Doubt:
Consider the morecore function is calling from some other function and receive 4 as int from argument(nu). I am having doubt in the following statements.
cp = sbrk(nu * sizeof(Header));
if (cp == (char *) -1)
return NULL;
up = (Header *) cp;
up->s.size = nu;
up is just a pointer to Header. But, still it does not point to any Header variable. sbrk allocates requested memory and returns current program break and it is stored in cp. Then the address stored in cp is casted and assigned to up. Now, the up contains the address which is returned by sbrk as a pointer to Header variable. Then the following statement occurs,
up->s.size = nu;
up
contains only the address returned by sbrk. Then how the above statement store the nu in the size variable.