0

I wrote a program that takes arguments from the command line and recursively builds a linked list using a struct. It also recursively prints the list. However, I am getting a segmentation fault when I try to run this program. My compiler is gcc. If someone can just tell me where the fault is occurring, that would be super helpful. Thanks!

#include <stdio.h>
#include <stdlib.h>

typedef struct list_node{
        char in_data;
        struct list_node *next_item;
        } list_node;

list_node *add_node(char input_x, list_node node_name);
void print_list(list_node *head_of_list);

int main(int argc, char *argv[]){
        int looper_1;
        int looper_2;
        char next_char;
        list_node *head_ptr;
        list_node head_node;
        for(looper_1 = 1; looper_1 < argc; looper_1++){
                for(looper_2 = 0; argv[looper_1][looper_2] != '\0'; looper_2++){
                        if(looper_1 == 1 && looper_2 == 0){
                        next_char = argv[looper_1][looper_2];
                        head_ptr = add_node(next_char, head_node);
                        }
                        else{
                        next_char = argv[looper_1][looper_2];
                        add_node(next_char, head_node);
                        }
                }
        }
        print_list(head_ptr);
        return 0;
}

list_node *add_node(char input_x, list_node node_name){
        list_node place_holder;
        list_node *place_ptr;
        if(node_name.in_data == -1){
                node_name.in_data = input_x;
                node_name.next_item = place_ptr;
        }
        else{
                node_name.next_item = add_node(input_x, place_holder);
        }
        list_node *new_ptr = &node_name;
        return new_ptr;
}

void print_list(list_node *head_of_list){
        if(head_of_list->in_data == -1){
                printf("NULL");
        }
        else{
                printf(" %c", head_of_list->in_data);
                print_list(head_of_list->next_item);
        }
        return;
}
jani
  • 107
  • 1
  • 5
  • 13

0 Answers0