I’m having some trouble copying a single linklist over to a double-linklist. Not sure what is going on but I’m having a gdb debugging error:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x0000000100000d86 in doublify (list=0x1001008c0) at lists.c:62
62 newDlist->item = curr->item;
The one-directional link list is working,
My .h Header File:
typedef struct _node {
Item item;
link next;
} node;
typedef struct _dnode *dlink;
typedef struct _dnode {
Item item;
dlink prev;
dlink next;
} dnode;
My Code:
link newLink (Item item){
link createLink = malloc(sizeof(node));
createLink->item = item;
return createLink;
}
link fromTo (int start, int end) {
link newList = NULL;
if(start <= end ){
newList = newLink(start);
newList->next = fromTo(start+1, end);
}
return newList;
}
//Heres where it isn't able to copy the linklist item over into the new dlist.
dlink doublify (link list) {
dlink newDlist = malloc (sizeof (dnode));
link curr = list;
while(curr != NULL){
newDlist->item = curr->item;
curr = curr->next;
newDlist = newDlist->next;
}
return newDlist;
}
The problem happens on the second iteration of the while loop. When you assign newDlist to the ‘next’ item, the ‘next’ field might contain any value. The thing is that malloc simply gives you a pointer to a data region where any values might be (it doesn’t clean it or init in some way).
You simply need to allocate a new node on each iteration and setup the pointers appropriately. Here is one of the ways how that can be done.