Brett Thompson wrote:

> > malloc() to allocate the ram when needed and would like to know if malloc()
> > uses Linux swap when it runs out of 'real' ram (i think it does because once
> 
> I'm almost 100% sure that it does... 
> 
> > the program got stuck in an endless loop and the harddrive went mad, then my
> > out of memory check kicked in and quit the program).
> 
> hee hee hee, well then, there you have it, evidence that malloc() (really 
> brk() I think?) uses swap.. :)
> 
> Hrm, not quite sure if malloc() itself uses swap, or causes Linux to swap 
> out other processes....

Well, ultimately malloc() obtains (virtual) memory from the kernel,
whether via brk/sbrk or anonymous mmap. The kernel deals with the
specifics of when virtual memory is located in physical RAM.

> > and i make a list with it, how do i free all the ram that the list uses? this
> > is the part of lists i could never work out.
> 
> Hrm, 'tis kind of tricky...
> 
> I think that what you have to do is to walk to the end of the list and 
> free, walking backwards...

With a singly-linked list, you would need O(n) memory to store all of
the back links.

> Er, hrm, actually, that's how I'd do it if you had a doubly-linked list, 
> where you've got a *prev as well as a *next pointer....

Unfortunately that would involve traversing the list twice, which is
an unnecessary performance hit. It's simpler to just store the `next'
pointer before you free the node.

BTW, something that I forgot to point out last time: for very small
structures (e.g. the 8-byte `struct node'), it's worth writing a
special-case allocator function, which allocates larger blocks of
memory using malloc (or equivalent), and then allocates individual
node structures from these.

In general, an allocator which allocates fixed-size blocks can be made
substantially more efficient than one which allocates blocks of
arbitrary sizes.

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to