dimanche 29 mars 2015

String Linked List in C gives Segmentation Fault

Below is a program I'm trying to create for a phone directory. This is the basic skeleton. I plan to add some more functions, once I get through this SegFault error. Please help.



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

struct node
{
char* pd;
struct node* next;
};
struct node* head;

void disp ()
{
struct node* temp = (struct node*) malloc (sizeof (struct node));
temp = head;
while (temp != NULL)
{
printf ("%s\n", temp -> pd);
temp = temp -> next;
}
free (temp);
}

void insert (char* s)
{
if (head == NULL)
{
head -> pd = s;
}
else
{
struct node* temp = (struct node*) malloc (sizeof (struct node));
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp -> pd = s;
free (temp);
}
}

void del (char* s)
{
if (head == NULL)
{
printf ("No element!");
}
else
{
struct node* prev = (struct node*) malloc (sizeof (struct node));
struct node* temp = (struct node*) malloc (sizeof (struct node));
temp = head;
while (temp -> pd == s)
{
prev = temp;
temp = temp -> next;
}
prev -> next = temp -> next;
free (temp);
free (prev);
}
}

main ()
{
int c;
char* str;
do
{
printf ("1: Display\n2. Add Contact\n3. Delete Contact\n0. Exit\n");
scanf ("%d", &c);
switch (c)
{
case 1:
disp ();
break;
case 2:
//printf ("lol");
scanf ("%s", str);
insert (str);
break;
case 3:
scanf ("%s", str);
del (str);
break;
default:
printf ("Try Again! :(");
}
} while (c != 0);
}


Error: Segmentation Fault (Core Dumped)


I can't insert anything into the list. It doesn't even seem to enter the function.


Aucun commentaire:

Enregistrer un commentaire