Code:
//
// Declaration for linked list of nodes.
//
typedef char *cstring;
typedef struct node *node_ref;
struct node {
cstring string;
node_ref link;
};
typedef struct list *list_ref;
struct list {
node_ref head;
};
int main (int argc, char **argv)
{
char *progname = basename (argv[0]);
list_ref list = NULL;
int linenr = 0;
char buffer[72];
for (linenr = 1; ; ++linenr)
{
char *nlpos = NULL;
node_ref temp = NULL;
printf("5");
// Read a line of input and check to see if it ends with
// a newline character. Print a message if not.
char *gotline = fgets (buffer, sizeof buffer, stdin);
printf("7");
if (gotline == NULL) break;
printf("6");
nlpos = strchr (buffer, '\n');
if (nlpos != NULL)
*nlpos = '\0';
else
{
fprintf (stderr, "%s: %d: unterminated line: %s\n",
progname, linenr, buffer);
}
printf("xyz");
node_ref prev = NULL;
node_ref curr = list->head;
printf("2");
// Find the insertion position.
while (curr != NULL)
{
if ( strcmp(buffer, curr->string) > 0)
break;
prev = curr;
curr = curr->link;
}
printf("3");
// Do the insertion.
temp = malloc (sizeof (struct node));
temp->string = buffer;
temp->link = curr;
if (prev == NULL)
list->head = temp;
else
prev->link = temp;
}
// Print the results in debug mode. Edit this so that only print if -d operand
/*printf ("%s: head= %p\n", argv[0], head);
while (head != NULL) {
node_ref old = head;
head = head->link;
printf ("%s: %p-> node {\n"
" string= %p->\"%s\",\n"
" link= %p}\n",
progname, (void*) old, (void*) old->string,
old->string, (void*) old->link);
};*/
return EXIT_SUCCESS;
}
So I'm getting a seg fault somewhere and I can't figure out where. I've tried commenting it various sections of my code to no avail. I have an idea of why seg faults occur, but my understanding is limited.
It is supposed to imitate this java program. I'm merely trying to convert the java code to C code.
Code:
import java.util.Scanner;
import static java.lang.System.*;
class sortlist
{
static class list_t
{
node_t head;
}
static class node_t
{
String item;
node_t link;
}
static void insertascending (list_t list, String newitem)
{
node_t prev = null;
node_t curr = list.head;
// Find the insertion position.
while (curr != null)
{
if (curr.item.compareTo (newitem) > 0)
break;
prev = curr;
curr = curr.link;
}
// Do the insertion.
node_t temp = new node_t();
temp.item = newitem;
temp.link = curr;
if (prev == null)
list.head = temp;
else
prev.link = temp;
}
public static void main (String[] args)
{
Scanner stdin = new Scanner (System.in);
list_t list = new list_t();
while (stdin.hasNextLine())
{
String line = stdin.nextLine();
insertascending (list, line);
}
for (node_t curr = list.head; curr != null; curr = curr.link)
{
out.printf ("%s%n", curr.item);
}
}
}