I am trying to use an array-based linked list to read in values from data.txt and then display those items. The list does not need to be ordered. Currently, it is only printing the last item on the list. I am not positive if I am reading the entire list currently or just the last word. I would appreciate any advice. I have made some changes since earlier. It compiles but I get a segfault which valgrind states "Invalid write or size 1".
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_SIZE 25
#define MAX_NODES 100
#define FILENAME "data.txt"
char buffer[WORD_SIZE];
int count = 0, i = 0;
typedef struct WORDNODE {
char word[WORD_SIZE];
struct WORDNODE *next;
} t_word_node;
t_word_node node_array[MAX_NODES];
t_word_node *free_list = NULL;
t_word_node *tail = NULL;
t_word_node *create_node(void);
void add_word(char *buffer, t_word_node **);
void node_init() {
for(int count = 0; count < MAX_NODES-2; count++) {
node_array[count].next = &node_array[count+1];
}
node_array[MAX_NODES - 1].next = NULL;
free_list = &node_array[0];
}
void add_word(char *buffer, t_word_node **list) {
t_word_node *temp = NULL;
t_word_node *last = NULL;
t_word_node *this = *list;
temp = create_node();
strcpy(temp->word, buffer);
while(this && strcmp(buffer, this->word) > 0) {
last = this;
this = this->next;
}
if(last == NULL) {
temp->next = this;
*list = temp;
} else {
last->next = temp;
temp->next = this;
}
}
t_word_node *create_node() {
t_word_node *new = NULL;
if(free_list != NULL)
{
new = free_list;
free_list = free_list->next;
}
return new;
}
void print_nodes(t_word_node *this) {
if(this == NULL) {
return;
}
while(this != NULL) {
printf("%s\n", this->word);
this = this->next;
}
}
int main() {
count = 0;
FILE *infile;
t_word_node *new_list = NULL;
node_init();
if((infile = fopen(FILENAME, "r")) != NULL) {
while (fscanf(infile, "%s", buffer) != EOF) {
add_word(buffer, &new_list);
}
fclose(infile);
}
print_nodes(new_list);
return 0;
}
data.txt
Kaleidoscope
Rainbow
Navy
Highway
Printer
Junk
Milk
Spectrum
Grapes
Earth
Horse
Sunglasses
Coffee-shop
Ice
Spice
Tennis racquet
Drill
Electricity
Fan
Meat
Clown
Weapon
Drink
Record
Spiral
Air
Data Base
Cycle
Snail
Child
Eraser
Meteor
Woman
Necklace
Festival
Eyes
Foot
Diamond
Chocolates
Explosive
Web
Rifle
Leather jacket
Aeroplane
Chisel
Hose
Flower
Space Shuttle
Radar
Hieroglyph
Ice-cream
Insect
Feather
Ears
Square
Software
Cup
Comet
Church
PaintBrush
Slave
Elephant
Sphere
Aircraft Carrier
Fork
Needle
Prison
Solid
Window
Dress
Knife
Spot Light
Onion
Horoscope
Chief
Crystal
Coffee
Microscope
Freeway
Fruit
Kitchen
Desk
Spoon
Pyramid
Restaurant
Adult
Potato
Egg
Telescope
Family
Sports-car
Television
Jet fighter
Thermometer
Wheelchair
X-ray
Sun
Worm
Church