Problem in Linked List

This is a discussion on Problem in Linked List within the C Programming forums, part of the General Programming Boards category; I have a "input.txt" : Code: 5 //number of number follow 1 3 6 2 4 and I want to ...

  1. #1
    hqt
    hqt is offline
    Registered User
    Join Date
    Aug 2011
    Posts
    115

    Question Problem in Linked List

    I have a "input.txt" :
    Code:
    5 //number of number follow
    1 3 6 2 4
    and I want to read them and create linked list for each element of sequence.
    this is my code:
    Code:
    #include <stdio.h>
    #define fi "input.txt"
    typedef struct tagNode{
        int info;
        struct tagNode *pNext;
    }Node;
    typedef struct tagList{
        Node *pHead;
        Node *pTail;
    }List;
    int main(){
        FILE *f;
        List *nList;
        nList=malloc(sizeof(List));
        f=fopen(fi,"r");
        int n;
        fscanf(f,"%d",&n);
        int i;
        int c;
        fscanf(f,"%d",&c);
        nList->pHead->info=c;
        nList->pHead->pNext=nList->pTail;
        nList->pTail->pNext=NULL;
        Node *tmp;
        tmp=malloc(sizeof(Node));
        for(i=2;i<=n;i++){
            fscanf(f,"%d",&c);
            tmp->info=c;
            tmp->pNext=nList->pHead;
            nList->pHead=tmp;
        }
        fclose(f);
        return 0;
    }
    But I have got some problem at line
    Code:
    danhsach->pHead->info=c;
    I have "segmentation fault".
    So, what am I wrong here, please help me, please.

    thanks
    Last edited by hqt; 08-15-2011 at 06:14 AM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,665
    nList is malloced but not initialised. Therefore nList->pHead does not point at anything, so modifying nList->pHead->info overwrites a random area of memory.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with linked list in c
    By hugoguan in forum C Programming
    Replies: 1
    Last Post: 12-10-2010, 05:28 AM
  2. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  3. syntax linked list problem & struct problem
    By beely in forum C Programming
    Replies: 5
    Last Post: 11-11-2002, 09:14 AM
  4. Linked list problem
    By Psycho in forum C++ Programming
    Replies: 3
    Last Post: 05-18-2002, 04:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21