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.

4
  • Note: They say you shouldn't cast the result of malloc() in C. Commented Mar 8, 2016 at 23:51
  • 2
    Suggest you use a debugger to help you find the problem. Commented Mar 8, 2016 at 23:53
  • Warning: The argument char **data isn't used in function insert() Commented Mar 8, 2016 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. Commented Mar 9, 2016 at 0:04

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for all of the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.