0

I am trying to implement a linked list in C. I believe I am creating and inserting elements correctly, but there is a segmentation fault every time I try to loop through. Here is my code for the linked list:

struct node {
char **data;
struct node *next;
};

Two global variables to store pointers to head and tail:

struct node *head;
struct node *tail;

Code to insert an element:

void insert(char **args)
{
    struct node* pointer = (struct node*)malloc(sizeof(struct node));
    pointer -> data = args;
    pointer -> next = NULL;
    if( head == NULL ) {
            head = pointer;
            tail = pointer;
    }
    else {
            tail -> next = pointer;
            tail = pointer;
    }
}

I then try to go through the list and print the data contents (this successfully prints the elements in the list, but then there is a segmentation fault):

int print_list(char **args)
{
    struct node *curPointer = head;
    if(curPointer == NULL) {
            printf("%s", "List is empty\n");
    }
    else {
            printf("%s", "List: ");
            do {
                    int i;
                    while(curPointer->data[i] != NULL) {
                            printf("%s", tail->data[i]);
                            i++;
                    }
                    printf("%s", "\n");
                    curPointer = curPointer->next;
            }while(curPointer->next != NULL);
    }
    return 1;
}

Other functions in my program that rely on looping through the list have a similar segmentation fault issue.

  • Note: They say [you shouldn't cast the result of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT Mar 08 '16 at 23:51
  • 2
    Suggest you use a debugger to help you find the problem. – kaylum Mar 08 '16 at 23:53
  • Warning: The argument `char **data` isn't used in function `insert()` – MikeCAT Mar 08 '16 at 23:55
  • In function `insert`, you declare argument `data`, but in the body you use `args`, which is presumably undefined. It seems the code you posted differs significantly from what you're trying to debug. Fix that. – Tom Karzes Mar 09 '16 at 00:04

1 Answers1

2
  • The value of local variable i having automatic storage duration is used without initializing, so it will invoke undefined behavior. Initialize i by replacing int i; to int i = 0;
  • When curPointer becomes NULL in curPointer = curPointer->next;, dereferencing curPointer in the condition curPointer->next != NULL have a big chance to cause Segmentation Fault.
    Try using curPointer != NULL instead of curPointer->next != NULL for the condition.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70