Velocity Reviews > Question regarding implementation details of malloc in K&R2

# Question regarding implementation details of malloc in K&R2

Barry Schwarz
Guest
Posts: n/a

 12-06-2007
On Sun, 2 Dec 2007 05:18:27 -0800 (PST), somenath
<(E-Mail Removed)> wrote:

>On Dec 2, 5:53 pm, James Kuyper <(E-Mail Removed)> wrote:
>> somenath wrote:
>> > 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
>> > My understanding is it is achieved by the following code segment

>>

>>
>> > 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 ?

>>
>> Because numnits is the number of 12-byte header units allocated. That's
>> enough for one 12-byte header and one 5-byte allocation, with 7 bytes
>> left over.

>
>According to the above explanation suppose user wants to allocate 5
>bytes ,malloc basically allocating more than 5 bytes . Here it is 7
>bytes which is for the user to be used . Is the behavior expected ?

The use is only requesting four bytes. This sample version of malloc
is allocating two contiguous Header units, 24 bytes. The first 12
bytes are for the malloc and free functions to use and the user is not
told about them. The second 12 bytes is the four the user requested
plus 8 more (since this malloc actually allocates Header units) which
the user is also not told about. This is the expected behavior for
this sample malloc only. No one is claiming that the "real" malloc in
any standard library actually works this way.

Remove del for email