James wrote:

> i'm writing a program that uses a linked list (actually it uses lots of
> linked lists, all linked together...) and it's all working nicely, i use
> 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
> 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).

All of the memory used by a user-space process is virtual memory. IOW,
it can be either RAM or swap. This applies to static data (global
variables and `static' local variables), the stack (return addresses,
function parameters, non-`static' local variables, and memory
allocated with alloca()), and the heap (memory allocated with malloc,
calloc etc).

The program code and read-only data (e.g. string literals) are even
more `virtual'; they are paged into memory from the executable as
required, so they never occupy any swap.

> Also, if i have a list defined as following:
> 
> typedef struct node node_t;
> struct node {
>       data *stuff;
>       node_t *next;
> }
> 
> 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.

If the memory referenced by `stuff' is dynamically allocated, you need
to free that as well. If you are using lots of dynamically allocated
structures, then you may be better off using a higher level language
that supports garbage collection.

> node_t *mylist, *temp;
> 
> build_a_list (mylist);
> while (mylist) {
>       temp = mylist;
>       free (mylist);
>       mylist = temp->next;
> }
> mylist = NULL;

This won't work reliably. The `free(mylist)' may modify (i.e. corrupt)
the node_t structure, so referencing it (via `temp->next') will have
undefined results. Instead, you need to read the `next' pointer before 
you free it, i.e.

        while (mylist)
        {
                temp = mylist->next;
                free (mylist);
                mylist = temp;
        }

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to