segmentation error during structured array (part of ip lookup)
I have been facing with this problem for almost 5 days.
This is part that grab IP address from file and store it as array.
so hash tables are supposed to be like this:
hashtable[length].which_element_of_table.IP_add
Code:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
//*************
struct ttyp
{
unsigned int index;
struct prtyp{
unsigned char len;
unsigned char port;
unsigned int ip;
} *prefix;
};
int num_entry=0;
struct ttyp *htable;
// READ IP FROM TEXT FILE
void read_table(char *str,unsigned int *ip,int *len,unsigned int *nexthop)
{
char tok[]="./";
char buf[100],*str1;
unsigned int n[4];
sprintf(buf,"%s\0",strtok(str,tok));
n[0]=atoi(buf);
sprintf(buf,"%s\0",strtok(NULL,tok));
n[1]=atoi(buf);
sprintf(buf,"%s\0",strtok(NULL,tok));
n[2]=atoi(buf);
sprintf(buf,"%s\0",strtok(NULL,tok));
n[3]=atoi(buf);
*nexthop=n[2];
str1=(char *)strtok(NULL,tok);
if(str1!=NULL)
{
sprintf(buf,"%s\0",str1);
*len=atoi(buf);
}
else
{
if(n[1]==0&&n[2]==0&&n[3]==0)
*len=8;
else if(n[2]==0&&n[3]==0)
*len=16;
else if(n[3]==0)
*len=24;
}
*ip=n[0];
*ip<<=8;
*ip+=n[1];
*ip<<=8;
*ip+=n[2];
*ip<<=8;
*ip+=n[3];
}
//BUILD HASH TABLE
void hash_table(char *file_name)
{
int count,z;
FILE *fp;
int len;
char string[100];
unsigned int ip,nexthop;
fp=fopen(file_name,"r");
while(fgets(string,50,fp)!=NULL)
{
read_table(string,&ip,&len,&nexthop);
num_entry++;
}
rewind(fp);
//prefix=(struct prtyp *)malloc(num_entry*sizeof(struct prtyp)); // i think this line is unnecessary, so i comment it
htable=(struct ttyp *)malloc(32*num_entry*sizeof(struct ttyp));
for(count=1; count<=32; count++){
htable[count].index=0; //counter initialization
}
while(fgets(string,50,fp)!=NULL){
read_table(string,&ip,&len,&nexthop);
z=htable[len].index;
htable[len].prefix[z].ip=ip;
htable[len].prefix[z].port=nexthop;
htable[len].index++;
}
}
//MAIN
int main(int argc,char *argv[])
{
hash_table(argv[1]);
printf("\n=================================");
printf("\nTotal prefix in txt file: %d", num_entry);
printf("\n=================================\n");
for(y=1;y<=32;y++){
if(htable[y].index)
printf("Table[%d] value numbers: %d\n",y,htable[y].index);
}
return0;
}
I thought i allocate enough memory htable pointer.
But still get:
Segmentation fault
Anyone help ? :)
Thanks,
Kane