Click to See Complete Forum and Search --> : Single Linked to Double linked C


goon12
03-02-2004, 04:17 PM
Hi - I have been looking at this all day causing segfaults and infinite loops...
I have this inside of a function

while( fread(read, 1, sizeof(SERVER), listfile) )
{
newNode = (S_LIST *)malloc(sizeof(S_LIST));
memcpy(newNode, read, sizeof(SERVER));
if( start == NULL )
{
start = newNode;
}
else
{
newNode->next = end;
end = newNode;

}

}
start->next = end;

That function then returns start, which I am able to use to loop through and show some information. Now here is the definition of type S_LIST

typedef struct server_list{
char name[100];
char addr[50];
int port_no;
int ports[50][50];
struct server_list *next;
struct server_list *prev;
} S_LIST;


I have been trying all day to get that to become a doubly linked list - and I can't seem to do it. The closest I can get is under "start->next = end" I put "end->prev = start" and the output looks like this

Server 0x8053e50 Address: 66.189.35.129 next = 0x8058dc0 prev = (nil)
Server 0x8058dc0 Address: 209.51.247.230 next = 0x8056608 prev = 0x8053e50
Server 0x8056608 Address: 209.51.247.235 next = (nil) prev = (nil)


My question is:
How to I turn that into a doubly linked instead of a singly linked list? :confused:

goon12
03-02-2004, 05:23 PM
Sorry I *think* I got it - going to do some more testing...



while( fread(read, 1, sizeof(SERVER), listfile) )
{
newNode = (S_LIST *)malloc(sizeof(S_LIST));
memcpy(newNode, read, sizeof(SERVER));
if( start == NULL )
{
start = newNode;
start->prev = NULL;
}
else
{
end->next = newNode;
newNode->prev = end;
}
end = newNode;
end->next = NULL;
}


Any comments would be good,
goon12

bwkaz
03-02-2004, 08:38 PM
Umm... if the SERVER structure has a different size or set of members than the S_LIST structure, it's expected to break... you're memcpy'ing from a SERVER to an S_LIST.

Besides that, if there are pointers in the SERVER structure, you HAVE to be reading it back in in the same process that you wrote it out in, otherwise the addresses that you wrote out will be massively incorrect. They were what the old process used; the new process won't have the same information at the same addresses.

And what if the file was written out on a big-endian machine? Any integers in the SERVER structure will be wrong if it's read in on a little-endian machine (like any Intel or AMD processor).