I'm experiencing a problem with a C program.  I am allocating two nodes
dynamically and creating a linked list.  The problem is when I return from
the function, it gives me a segmentation fault.  My code looks fine, and
it runs fine under digital unix.  Do I have to do something different with
linux when using dynamic memory?  I've attached my code if someone would
look at it.  Thanks for the help.


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



struct linked_list 
  {
    char                      name[50];
    struct linked_list        *next;
  };

typedef struct linked_list ELEMENT;
typedef ELEMENT *link;

/* Function prototypes */

link read_file(void);


/*-----------------------------------------------------------*/
int main(void)
{
  link h;
  
  printf("\n%s\n", "hello1");

  h = read_file();
  
  printf("\n\n%s\n\n", "back");

  printf("\%s\n", h->name);

  printf("\n%s\n", "hello");

  return 0;
}


link read_file(void)
{
  char filename; FILE *ifp;
  link extraptr = NULL;
  link headptr = NULL;


  printf("%s", "Enter file name: ");
  scanf("%s", &filename);

  ifp = fopen(&filename, "r"); /* open file */

  if (ifp == NULL) /* check if file exists */
    {
      printf("\n%s%s%s\n", "Error, the file \"", &filename, "\" does not exist or 
cannot be accessed.");
      exit(1);
    }
  else
    printf("\n%s%s%s\n\n", "Attempting to open \"", &filename, "\" ...");
  
  
  headptr = malloc(sizeof(ELEMENT)); /* create head node */
  fscanf(ifp, "%s", headptr->name); /* read first name into array */
  headptr->next = NULL; /* mark link to next node as null */
  
  extraptr = headptr;

  /*  while ((extraptr->name) != "") */
  {    
      extraptr->next = malloc(sizeof(ELEMENT));
      extraptr = extraptr->next;

      fscanf(ifp, "%s", extraptr->name);

      extraptr->next = NULL;
  } 
 
  fclose(ifp); /* close file */

  printf("%s", "done reading...");
  
  printf("\n%s\n\n", "hello");
  
  return headptr; 

}





Reply via email to