lufork lufork - 1 year ago 83
C Question

C linked list head pointing to itself?

Here is the a code snippet of my addNode method. For some reason my head node is pointing to itself. Whenever I try to print out the contents of the linked list, all I get is my head's contents.

I know about linked lists already, but I was testing to see if we can use direct structs instead of their pointers to use in linked lists.

struct Node{
char* data;
struct Node* next;

// Global variables
int numberOfElements = 0;
struct Node* head = NULL;

void addNode(char* inputString){
struct Node newNode; = inputString;
if(numberOfElements != 0){ = head;
else{ = NULL;
head = &newNode;

P.S. If the error cannot be deduced from here, then I guess error is somewhere else in my code. If so, I can put that in here as well.


Answer Source
  • Firstly, your code declares a local variable newNode and attempts to include it into the list.

    Local variables are destroyed when function exits. This is what happens to newNode when addNode exits. And your list ends up in invalid state - your head ends up pointing to nowhere. That's what leads to the behavior you are observing. (The behavior is most definitely undefined when you attempt to print it out.)

    You have to allocate your node objects in dynamic memory to make sure they live "forever" or as long as you want them to.

  • Secondly, your node addition logic is unnecessarily overcomplicated. It appears that you always plan to add a new node to the beginning of the list. In this case the next field of the new node should always be set to point to the former head. The entire if with = NULL branch is completely unnecessary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download