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 05:14 AM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,255
    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%.

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, 04:28 AM
  2. Replies: 6
    Last Post: 03-02-2005, 01:45 AM
  3. syntax linked list problem & struct problem
    By beely in forum C Programming
    Replies: 5
    Last Post: 11-11-2002, 08:14 AM
  4. Linked list problem
    By Psycho in forum C++ Programming
    Replies: 3
    Last Post: 05-18-2002, 03:14 PM

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