0

As part of an assignment, I am having a program read in the names and id of people from a file, and saving them in separate linked lists. I have a nested while loop to traverse the list until it reaches the end, and then assign the values at the end. Unfortunately the program keeps crashing while reading and it seems to revolve around the second while loop.

Here is the struct established before the main()

struct node
{
    char name[50];
    int id;
    struct node *next;
}*start;

Here is the function itself:

void read()
{
   int tempNum = 0, id, jack = 0;
   char name[50];

   struct node *temp, *right;
   temp = start;

   FILE *ifp = fopen("AssignmentOneInput.txt", "r");
   while(fscanf(ifp," %s", &name) != EOF)
   {

       fscanf(ifp, " %[^,]s, %[^/n]d", &name, &id);

       temp = (struct node *)malloc(sizeof(struct node));

       strcpy(temp->name,name);
       temp->id = id;

       right = (struct node *)start;

       printf("test number one\n");
       while(right->next != NULL)
       {
            printf("test number two\n");
            right = right->next;
       }
        printf("test number three\n");


       right->next = temp;
       right = temp;

       right->next = NULL;

   }

}

As for its implementation in the main function, it is the very first function called, so it looks a little like:

main()
{
  read();
Dakrid
  • 1
  • 1
  • 5
  • Give us a complete program with main(). Tell us exactly where it crashes and what is the exact message. – Mike Nakis Feb 06 '15 at 19:38
  • What is the definition of `node`? – Martin Feb 06 '15 at 19:38
  • Do you ever initialize a node's `next` to NULL? – AndyG Feb 06 '15 at 19:38
  • [In C don't cast the return of `malloc`.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Some programmer dude Feb 06 '15 at 19:41
  • 1
    Also, what happens if `start` is `NULL`? Or if it's not initialized? Or points to unallocated memory? There are to many unknowns in your program, please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us. Together with a stack backtrace when the crash happens. – Some programmer dude Feb 06 '15 at 19:42
  • When it crashes, there are no errors in the build log. Only the "assignment.exe has stopped working" Also, the error appears around the second while loop, as it prints out the first "printf" test but then crashes before printing the second one. – Dakrid Feb 06 '15 at 19:44

1 Answers1

0

I guess thatstart is a global variable? Then it will be zero-initialized by the compiler and C runtime system. That means it will, as a pointer, be initialized to NULL. So when you use it uninitialized in your code it will be NULL and you have undefined behavior when you dereference the pointer. And undefined behavior is arguably the most common cause of crashes.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621