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;
   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");
   printf("file opened\n");
    {   printf("%s\n%s\n",m.ip,ip2);
        { printf("string matched..exiting...\n");
          return 0;
      fprintf(ifile,"%s%c%d",ip2,' ',k+1);  
   printf("file not opened\n");
   printf("file opened\n");
   fprintf(ifile1,"%d%c",m.num,' ');



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 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.

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.