Thread: segmentation fault

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    94

    segmentation fault

    Im getting a segmentation error....can anyone help please
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct node
    {
      char *data;
      struct node *next;
    };
    
    
    int main()
    {
     
     struct node *head, *curr;
     int i=0;
     char *str=malloc(5);
     
    /* head=NULL; */
     head=(struct node*) malloc (sizeof(struct node));
     curr=head;
    
      printf("\nPlease enter data :   ");
     
      for (i=0; i<5; i++)
      {
          str[i]=getchar();
    
          if (str[i]=='\n')
            i=5;
      }
       
       strcpy(str, curr->data);
       printf("\n Data is : %s", curr->data);
    
     return 0;
    }
    simple is always an understatement.....

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    The order of the arguments to the strcpy function appear to be reversed and you haven't allocated any space for the data pointer within the node pointed to by curr.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    23
    Also the string should be terminated with '\0' to make your printf look nice

    str[i] = '\0'

    aswell as

    curr->data = (char *) malloc(5 * sizeof(char));

    to allocate memory for a 5 char string

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Re: Segmentation fault
    By turkish_van in forum C Programming
    Replies: 8
    Last Post: 01-20-2007, 05:50 PM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM