简体   繁体   中英

Segmentation fault in getc()

I am developing a linked list in C. And I am getting the data from a txt file. But when I try to run the program, it gives me a segmentation fault of getc() Here's the code,

#include<stdio.h>
#include<stdlib.h>
struct node{
            char surname[100];
        int number[1o0];
        char name[100];
        struct node *next;
       };
typedef struct node Node;

int main()
{
FILE *ifp;
Node first ,*current;
//current =&first;
int i=0,j=0;
int ch;
char num[100],name[100];

ifp = fopen("tele.txt","r");

 while (ch != EOF)
{       
    while(i<4)
    {
      ch = getc(ifp);
      num[i++] = ch;
    }
    num[i] = '\0'; 
    i=0;
    while(ch !='\n')
    {    
       ch = getc(ifp);
       if(ch != '\t')
         name[j++]=ch;
    }
    name[j] = '\0'; 
    //ch = '\0';

    printf("Number %s\nName %s\n ",num,name);
    j=0;

}

fclose(ifp);
}

and the error I am getting while I try to run the program is,

Program received signal SIGSEGV, Segmentation fault. 0x0000003c0ee68dfa in getc () from /lib64/libc.so.6

Kindly guide me in this. thanks in advance.


The most likely reason is that it can't open the file.

Check that ifp is not NULL immediately after you've called fopen("tele.txt","r") . If it is NULL, errno will give you more detail of what went wrong (lots of possible reasons, some of which are: the file doesn't exist, you don't have permissions to access it, or you're in the wrong directory.)

There are also several issues around ch itself, probably unrelated to the crash:

  • ch is not initialized, so the while (ch != EOF) may or may not be entered [thanks to @Dirk for pointing this out];
  • while(ch !='\\n') is a bit dodgy in that if you encouter EOF , you end up in an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM