S
somenath
Hi All ,
As a process of my C language learning I was trying to learn how
malloc can be implemented from K&R2 .But I am not able to
understand few points . It would be very much helpful if some body
give some inputs in the bellow mentioned points.
Point 1) I page 186 it is said that "In malloc, the requested size in
characters is rounded up to the proper number of header-sized
units; the block that will be allocated contains one more unit, for
the header itself, and this is the value recorded in the size field of
the header."
My understanding is it is achieved by the following code segment
nunits = (nbytes+sizeof(Header)-1)/sizeof(header) + 1;
but I am not getting how it is done ? Suppose user has requested for 4
bypes so "nbytes" will be = 5
now nunits = 5 + 12 -1 /12 + 1 /*Assume that sizeof(Header) = 12*/
= 16/12 + 1
= 1+ 1 = 2
So my doubt is how 2 will help to get 5 bytes ?
Point 2 ) Why "return (void *)(p+1);" is used why p is not returned ?
My understanding is p contains the starting address of the
requested size so we should return (void *) p .
Point 3 ) In "morecore" function "free((void *)(up+1));" is used to
add up in the free list . My question is why we are not adding "up"
instead of "up+1" ?
Point 4)in the "free" function "bp = (Header *)ap - 1; /* point to
block header */
Is used to point to the header . Why ap is not used ?
I am really confused . Please some body help me to understand the
logic behind this implementation .
Regards,
Somenath
As a process of my C language learning I was trying to learn how
malloc can be implemented from K&R2 .But I am not able to
understand few points . It would be very much helpful if some body
give some inputs in the bellow mentioned points.
Point 1) I page 186 it is said that "In malloc, the requested size in
characters is rounded up to the proper number of header-sized
units; the block that will be allocated contains one more unit, for
the header itself, and this is the value recorded in the size field of
the header."
My understanding is it is achieved by the following code segment
nunits = (nbytes+sizeof(Header)-1)/sizeof(header) + 1;
but I am not getting how it is done ? Suppose user has requested for 4
bypes so "nbytes" will be = 5
now nunits = 5 + 12 -1 /12 + 1 /*Assume that sizeof(Header) = 12*/
= 16/12 + 1
= 1+ 1 = 2
So my doubt is how 2 will help to get 5 bytes ?
Point 2 ) Why "return (void *)(p+1);" is used why p is not returned ?
My understanding is p contains the starting address of the
requested size so we should return (void *) p .
Point 3 ) In "morecore" function "free((void *)(up+1));" is used to
add up in the free list . My question is why we are not adding "up"
instead of "up+1" ?
Point 4)in the "free" function "bp = (Header *)ap - 1; /* point to
block header */
Is used to point to the header . Why ap is not used ?
I am really confused . Please some body help me to understand the
logic behind this implementation .
Regards,
Somenath