hi,i am new to C
i am constantly getting the error "Segmentation fault" and i dont know how to deal with it. I can't find an error in my code.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pcap.h>


int main()
{ 
   FILE *ifile,*ifile1;
   char* ip2;
   ip2="192.168.1.1";
   int k = 20;
  
   struct map1 
   { char* ip;
     int num;
   }; struct map1 m;
   
   ifile = fopen("/home/hp/Desktop/tcpdump/map.txt","a+");
   if(ifile == NULL)
   printf("file not opened\n");
   else
   printf("file opened\n");
   //printf("%s\n",ip);
   //printf("%d\n",strlen(ip));
 
   while((fscanf(ifile,"%s%d",m.ip,&m.num))!=EOF)
    {   printf("%s\n%s\n",m.ip,ip2);
        if((strcmp(m.ip,ip2))==0)
        { printf("string matched..exiting...\n");
          return 0;
	} 
    }
      
      m.num=k+1; 
      fprintf(ifile,"%s%c%d",ip2,' ',k+1);  
      fputc('\n',ifile);
     
   fclose(ifile);
   
   ifile1=fopen("/home/hp/Desktop/tcpdump/edges.txt","a+");
   if(ifile1==NULL)
   printf("file not opened\n");
   else
   printf("file opened\n");
   
   //printf("%d\n",m.num);
   fprintf(ifile1,"%d%c",m.num,' ');

   fclose(ifile1);

}

When i run this code for the first time,it runs perfectly.
On the display screen i get:
File opened
File opened
Two files are made: map.txt which has 192.168.1.1 and edges.txt which has 21.

When I run it for the second time(ie.when it enters the while loop), it returns:
File opened
Segementation fault

I know the error is related to the wrong use of arrays and pointers but I am not able to figure it out.
Please help me.

>while((fscanf(ifile,"%s%d",m.ip,&m.num))!=EOF)
I'd start with the fact that when fscanf is called, m.ip is an uninitialized pointer.

On a side note, using EOF as the test against fscanf isn't wrong, but it's not completely right either. One test case where your condition fails is if the string reads successfully, but the integer fails. In that case fscanf will return the number of successful conversions. As such, it's best practice to test for the number of expected conversions:

while (fscanf(ifile,"%s%d", m.ip, &m.num) != 2)

This also covers the case where fscanf returns EOF, because EOF is guaranteed to be a negative quantity.

> m.ip=0

Is that how I should initialise the pointer?

This article has been dead for over six months. Start a new discussion instead.