Hello all,
I've come across a strange bug in my code while attempting to make a simple singly linked list. I first noticed the bug while attempting to append multiple items to the list and then print their contents, which caused an infinite loop. After some digging, I discovered that the cause seemed to be a problem with my pointers, and I was eventually able to pare it down until I worked out the exact spot that was causing me trouble. The problem is, I don't know why it's causing issues. Here is the code, cut down as much as I could get it and still reproduce the bug:
Code:
#include <stdio.h>
#include <stdlib.h>
struct SingleNode {
int data;
struct SingleNode *next;
};
struct SingleList {
struct SingleNode *head;
};
struct SingleNode newSingleNode(int data)
{
struct SingleNode new;
new.data = data;
new.next = NULL;
return new;
}
struct SingleList newSingleList()
{
struct SingleList new;
new.head = NULL;
return new;
}
void nodeGlitch(struct SingleList *s, struct SingleNode n)
{
}
void appendNode(struct SingleList *s, struct SingleNode n)
{
if (s->head == NULL)
{
s->head = &n;
}
}
int main()
{
struct SingleList list = newSingleList();
struct SingleNode a = newSingleNode(3);
struct SingleNode b = newSingleNode(5);
appendNode(&list, a);
printf("Head is %i\n", list.head->data);
nodeGlitch(&alpha, b);
printf("Head is %i\n", list.head->data);
printf("a is %i\n", list.head);
return 0;
}
This program produces the following output:
Code:
Head is 3
Head is 5
a is 3
a is unchanged, but the head of list now has "5" in its data field - in other words, it now points to b. This happens even though the only thing that changed between the two printf() calls was a call to the empty function nodeGlitch(). I assume it must have something to do with the arguments passed into nodeGlitch(), but I don't see why an empty function would overwrite a pointer in its first argument with the address of its second. Anyone know why this would happen, and how I can avoid it passing structs to functions in the future?