I am attempting to construct my first linked list, and having read a basic introduction, have done the following. Firstly, declare a linked list node as:
struct errorNode {
uint8 error;
struct errorNode* next;
};
Secondly, define the first node globally as:
struct errorNode errorList = {0, NULL};
This has been done to allow each of the libraries that make up my current project to insert errors into a common list. The function to do this is:
void errorListWrite(uint8 error) {
struct errorNode* newNode = malloc(sizeof(struct errorNode));
newNode->error = error;
newNode->next = &errorList;
errorList = *newNode;
}
Whilst this compiles without error, it does not function as expected. I thnk the problem is with the last two statements of the list write function, but I am unsure. A hint as to what I am doing wrong would be most appreciated.
The problem is that you create a circular list.
So
newNodelinks to the global node.This is equivalent to
errorList.error = newNode->error; errorList.next = newNode->next;.So now
errorListlinks to the global node. Oops.What you could do instead, is insert the new node after the global node in the list:
This is assuming that you want a global node at all. If you don’t, then you could start with
struct errorNode *errorList = 0;, and add a new node like this:When you come to use the list, your list-traversal may look a little different. With a global pointer-to-node you’ll start with a pointer to the first node, that you must check for null before using. With a global node you’d start with a node that definitely exists, but whose next pointer might be null.