Hey Guys,
So I'm working on a bigger project but trying to implement some Linked List functionality into it and I keep getting this segmentation fault at the same spot and I've checked examples and such and my code (I think) is in line with theirs but mine's not working. I'm a little rusty on C and just getting back into it so maybe it's something simple. I thought I had pointers down pat but maybe I don't. If someone see's what's causing this I'd appreciate it!
I'm trying to implement a doubly-linked list:
listtest.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include "list.h"
int main(void)
{
//Vars
List *list;
Node *head;
Node *node;
int r;
//Setup
if((list = (List *)malloc(sizeof(struct List))) == NULL)
{
printf("List: Memory Allocation Failed...\n");
return 0;
}
if((head = (Node *)malloc(sizeof(struct Node))) == NULL)
{
printf("Head: Memory Allocation Failed...\n");
return 0;
}
head->value = 5;
r = init(&list, &head);
if(r == -1)
{
printf("Linked List: init() Failed...\n");
return 0;
}
//Setup Additional Node
if((node = (Node *)malloc(sizeof(struct Node))) == NULL)
{
printf("Linked List: add() Failed...\n");
return 0;
}
r = add(&list, &node);
if(r == -1)
{
printf("Linked List: add() Failed...\n");
return 0;
}
//Print
printList(list);
//return
return 1;
}
list.h
Code:
#ifndef _LIST_H_
#define _LIST_H_
#ifndef _STDDEF_H
#include <stddef.h>
#endif
typedef struct Node
{
unsigned index;
unsigned value;
struct Node *next;
struct Node *prev;
}Node;
typedef struct List
{
unsigned size;
struct Node *head;
struct Node *tail;
}List;
int init(List *list, Node *head);
int add(List *list, Node *node);
void printList(List *list);
#endif
list.c
Code:
//Includes
#include "list.h"
//Pre-Processors
#ifndef _STDIO_H
#include <stdio.h>
#endif
#ifndef _STDLIB_H
#include <stdlib.h>
#endif
//Function Definitions
int init(List *list, Node *head)
{
if(list == NULL)
{
return -1;
}
if(head == NULL)
{
return -1;
}
list->head = head;
list->size = 1;
head->index = 0;
head->prev = NULL;
head->next = NULL;
return 1;
}
int add(List *list, Node *node)
{
//Vars
Node *temp;
//Checks
if(list == NULL)
{
return -1;
}
if(node == NULL)
{
return -1;
}
//Move to the end of the list
temp = list->head;
while(temp->next != NULL)
{
temp = temp->next;
}
//Set the links
temp->next = node;
node->prev = temp;
node->index = list->size;
//Increment the size
list->size++;
//Update the tail nodes
list->tail = node;
return 1;
}
void printList(List *list)
{
Node *temp;
temp = list->head;
while(temp->next != NULL)
{
printf("Index: %d\tValue: %d\n", temp->index, temp->value);
temp = temp->next;
}
}
The error's occurring in the list.c (above) on line 53, where the add() function is traversing to the end of the list:
Code:
...
while(temp->next != NULL)
...
If it matters (but I don't think it does) I'm on 32-bit *nix. The program's just crashing with a Seg Fault and gdb is pointing me to that line.
Thanks!