Hi there James (and everybody else too)!
Well, I'll give you what tiny shreds of knowledge I have on linked lists,
probably somebody else can give you *much* better advice... Anyway,
maaaaybe I'll be of some use, so here goes:
On Thu, 6 Aug 1998, 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
Cool, sounds like you did a good job with that part.
> 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....
> Also, if i have a list defined as following:
>
> typedef struct node node_t;
> struct node {
> data *stuff;
> node_t *next;
> }
Looks good...
> 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...
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....
Something perhaps like (I'm writing this right now, haven't tested it,
you can probably come up with something better):
/* Walks down a list, free()ing those nodes which it passes... */
/* not sure if this works, just cobbled it together real quick for fun :) */
void clobber_list(note_t *head)
{
note_t *list, *tmp;
tmp = head;
if (tmp->next != NULL)
list = tmp->next;
while (list->next != NULL) {
free(tmp);
tmp = list;
list = list->next;
}
free(list);
}
I dunno, something like that.... Go down the list, keeping a pointer to
the previous node, and free that...
Hrm, well, I found a little bug in your code here, although the idea
behind it was all right:
> while (mylist) {
> temp = mylist;
These next two lines are the bug...
> free (mylist);
> mylist = temp->next;
eek!! Quite sorry, but you've just free()ed mylist, to which temp was
pointing...
So when you say, "temp->next", you're dereferencing, trying to access, an
area of memory that is no longer yours... Just asking for a segfault, 'tis!
Anyway, hope I was of a tiny bit of help...
Keep up the Linux programming! :) :)
Long Live Linux!!!
-Brett