I was making a doubly-linked list in C and before it had three variables as its data (two ints and a bool after I threw in typedef int bool) and the two pointers next and prev. I inserted in the back with a function that roughly said
void insert(list *l, int x, int y, bool z)
{
node *n = makeNode(x, y, z);
if(isEmpty(*l))
l->head = l->tail = NULL;
else
{
l->tail->next = n;
n->prev = l->tail;
l->tail = n;
}
}
And my makeNode function said something like:
node *makeNode(int x, int y, bool z)
{
node *n = malloc(sizeof(n));
n -> x = x;
n -> y = y;
n -> z = z;
n -> next = NULL;
n -> prev = NULL;
return n;
}
So then I print it out with something that looked like:
void printList(list l)
{
node *i;
for(i = list.head; i != NULL; i = i -> next)
printf("%d %d %d\n", i -> x, i -> y, i -> z);
printf("\n");
}
That one worked perfectly, but then I had
void reversePrintList(list l)
{
node *i;
for(i = list.tail; i != NULL; i = i -> prev)
printf("%d %d %d\n", i -> x, i -> y, i -> z);
printf("\n");
}
And that one segfaulted. After playing around with the code, for some odd reason, while the “next” pointers remained intact every time, the “prev” pointers did not point to the nodes I originally had them pointing to, and apparently they weren’t pointing at NULL either.
Furthermore, earlier I was trying to implement it as a circular doubly-linked list and for some reason still the next pointers worked just fine but the prev pointers once again were pointing somewhere strange.
But what’s really weird about this is that when the nodes only contained one int, everything worked perfectly on both the linear and circular doubly-linked list. And when I do a few syntactic changes to translate the code to C++, it works perfectly with the bigger node. I looked all over and there was no code I wrote that was supposed to alter the prev pointers outside of the insert function. So what is going on to mess up the prev pointers and only the prev pointers when I used a bigger node in C?
Thanks!
Nerd With a Vengeance
P.S. Here are my structs
typedef struct node{
int x;
int y;
bool z;
struct node *next;
struct node *prev;
} node;
typedef struct list{
node *head;
node *tail;
} list;
This doesn’t make any sense. You want to allocate enough bytes to hold a node, not a pointer to a node. Try: