-1


I am getting some problems in my code and I can not fix it. Can anybody catch the flaw in mycode? I wanna get city distance from input files and copy the city names in map without repetition.My problem is segmentation fault. the input file consist of several lines two cities names and distance between them and i try to get the cities name and copied them to the double pointer named as map. P.S sorry for poor english

city1[0]  = (char*)malloc(sizeof(char)*10);                     
city2[0]  = (char*)malloc(sizeof(char)*10);
map[0] = (char*)malloc(sizeof(char)*10);
map[1] = (char*) malloc(sizeof(char)*10);
map[2] = (char*) malloc(sizeof(char));
map[2] = NULL;
fscanf(data, "%s %s %d", city1[0], city2[0], &distance);
strcpy(map[0],city1[0]);
strcpy(map[1],city2[0]);                  
j=2,i=1;
while(fscanf(data, "%s %s %d",city1[i],city2[i], &distance)!=EOF){
    city1[i+1] = (char*)malloc(sizeof(char) *10);
    city2[i+1] = (char*)malloc(sizeof(char)*10);
    if(checker(map,city1[i])==1){
        map = realloc(map, sizeof(char*)*(j));
        map[j] = (char*) malloc(sizeof(char));
        strcpy(map[j], city1[i]);
        map[j+1] = (char*) malloc(sizeof(char));
        map[j+1] != NULL;
        j++;
    }
    if(checker(map,city2[i])==1){
        map = realloc(map, sizeof(char*)*(j));
        map[j] = (char*) malloc(sizeof(char));
        map[j+1] = (char*) malloc(sizeof(char));
        strcpy(map[j], city2[i]); 
        map[j+1] = NULL;   j++;
    }
}

1 Answers1

0

Show the definitions of the variables that you are using.

I think you have some misunderstanding regarding the use of malloc() to dynamically allocate space for strings. You are allocating space for single characters, using many calls to malloc(). This seems very confused.

Also please try to be more clear regarding what your code is supposed to do.

unwind
  • 391,730
  • 64
  • 469
  • 606