I'm having a segmentation error whenever I try to print the list I've created. I'm confused to why this is happening. It seems to be happening whenever I try to access node->data with printf. I'm doing this on my own to learn programming and creating abstract data types and familiarization with c, this is not a school assignment. Another thing, this compiles without any problem. It is only when I try to call printlist or delete node that I run into a segmentation fault.
Code:
List.h:
#include <stdio.h>
#include <stdlib.h>
typedef int node_data;
struct node {
struct node *next;
struct node *prev;
int data;
};
struct node *conductor = NULL;
struct node *begin = NULL;
void init() {
/* Initializes this library,
call before any other functions
are called. */
conductor = NULL;
}
int emptyList () {
/* Checks to see if the list is empty,
and returns true if so */
if (conductor = NULL) {
return 1;
}else{
return 0;
}
}
void newNode () {
/* Creates a new node */
struct node *temp = malloc(sizeof(struct node));
printf("Input data for the new node\n");
temp->data = scanf("%d", &(temp->data));
if (emptyList()){
begin = temp;
temp->next = temp;
temp->prev = temp;
conductor = temp;
}else{
temp->prev = conductor;
temp->next = begin;
}
}
void printList() {
/* Prints the list */
int condition;
struct node *temp;
temp = conductor;
do {
int x = conductor->data;
printf("%d\n", x);
conductor = conductor->next;
if (conductor = temp) {
int condition = 0;
}else{
int condition = 1;
}
}while(condition != 0);
conductor = temp;
}
void freeNode() {
/* Deletes the node that the conductor is pointing to
then re-links the broken list */
struct node *temp;
int choose;
if (emptyList()){
printf("The list is empty!\n");
}else{
do {
printf("%d, is here, delete this node?\n", conductor->data);
scanf("%d",&choose);
if (choose){
temp = conductor;
conductor->prev = conductor->next;
conductor = conductor->next;
free(temp);
printf("Deleting node...\n");
if (emptyList()){
printf("The list is empty! Re-initalise and star over!\n");
break;
}
}else{
conductor = conductor->next;
}
}
while(choose != 1);
}
}
Code:
main.c:
#include "list.h"
#include <stdio.h>
int main()
{
int menu;
int loop = 0;
/*printf("1. Make a new node\n"
"2. Print the list\n"
"3. Delete a node\n");
//scanf("%d",&menu);
printf("Initialising list\n");
init();
printf("List initialised!\n");
*/
do {
printf("1. Make a new node\n"
"2. Print the list\n"
"3. Delete a node\n"
"4. Initialise List\n");
//scanf("%d",&menu);
/* printf("Initialising list\n");
init();
printf("List initialised!\n");
*/
scanf("%d",&menu);
switch (menu)
{
case 1:
newNode();
printf("newNode called\n");
break;
case 2:
printList();
printf("List printed!\n");
break;
case 3:
freeNode();
printf("Node deleted!\n");
break;
case 4:
init();
printf("List initialised!\n");
break;
}
printf("Again?\n");
scanf("%d",&loop);
}while (loop);
printf("Execution successful, terminating...\n");
return 0;
}
Thanks for your help